7 Code Snippets for WordPress

application Code Snippets plug-in management code , you can solve some common functional requirements in the process of building WordPress without installing additional plug-ins, such as Install Google analytics tracking code . The following is a record of the code snippets I often use in building foreign trade websites and personal blogs.

Original: https://loyseo.com/code-snipp...

How to disable loading of woocommerce on WordPress articles / pages JS (Javascript) and Css file?

Woocomerce will load several css and js on each page by default, which has an impact on the speed of the website. The following code is code snippets In plug-in Add a new snippet , it can remove the css and js of woocommerce from pages other than shopping cart, settlement, account and product.

/** Disable All WooCommerce  Styles and Scripts Except Shop Pages*/
add\_action( 'wp\_enqueue\_scripts', 'dequeue\_woocommerce\_styles\_scripts', 99 );
function dequeue\_woocommerce\_styles_scripts() {
if ( function\_exists( 'is\_woocommerce' ) ) {
if ( ! is\_woocommerce() && ! is\_cart() && ! is_checkout() ) {
# Styles
wp\_dequeue\_style( 'woocommerce-general' );
wp\_dequeue\_style( 'woocommerce-layout' );
wp\_dequeue\_style( 'woocommerce-smallscreen' );
wp\_dequeue\_style( 'woocommerce\_frontend\_styles' );
wp\_dequeue\_style( 'woocommerce\_fancybox\_styles' );
wp\_dequeue\_style( 'woocommerce\_chosen\_styles' );
wp\_dequeue\_style( 'woocommerce\_prettyPhoto\_css' );
# Scripts
wp\_dequeue\_script( 'wc\_price\_slider' );
wp\_dequeue\_script( 'wc-single-product' );
wp\_dequeue\_script( 'wc-add-to-cart' );
wp\_dequeue\_script( 'wc-cart-fragments' );
wp\_dequeue\_script( 'wc-checkout' );
wp\_dequeue\_script( 'wc-add-to-cart-variation' );
wp\_dequeue\_script( 'wc-single-product' );
wp\_dequeue\_script( 'wc-cart' );
wp\_dequeue\_script( 'wc-chosen' );
wp\_dequeue\_script( 'woocommerce' );
wp\_dequeue\_script( 'prettyPhoto' );
wp\_dequeue\_script( 'prettyPhoto-init' );
wp\_dequeue\_script( 'jquery-blockui' );
wp\_dequeue\_script( 'jquery-placeholder' );
wp\_dequeue\_script( 'fancybox' );
wp\_dequeue\_script( 'jqueryui' );
}
}
}

How to disable XML-RPC for WordPress

WordPress sites rarely need to enable XML-RPC, but enabling it can cause a lot of security problems. If you use the WordPress application, you need to enable it. This code snippet will disable XML-RPC to improve site security.

add\_filter('xmlrpc\_enabled', '\_\_return\_false');

How to install Google Analytics tracking code with code snippets

Please put the tracking code obtained from Google analytics into the following code segment

add\_action( 'wp\_head', function () { ?>
    
Paste here Google Analytics Tracking code for
<?php });

Related tutorials: How to install Google Analytics tracking code for WordPress website

How to remove / hide the Url field in WordPress comments

The following code can remove / hide the comment URL field in some WordPress topics. If you find that it cannot be removed after use, it indicates that the topics are incompatible. You can search in Google: Remove Website field from the Comment Form in XXX theme and change XXX to your topic name.

function remove\_comment\_fields($fields) {
unset($fields\['url'\]);
return $fields;
}
add\_filter('comment\_form\_default\_fields','remove\_comment\_fields');

For example, in the free version of astra theme, the url field of hidden comments uses the following code

function wpd\_remove\_comment\_website\_field( $fields ) {
    unset( $fields\['url'\] );
    
    return $fields;
}
add\_filter( 'comment\_form\_default\_fields', 'wpd\_remove\_comment\_website\_field', 99 );

In the paid version of astra theme, remove the url field of the comment and use the following code

function wpd\_remove\_comment\_website\_field( $fields ) {
    unset( $fields\['url'\] );
    
    return $fields;
}
add\_filter( 'astra\_comment\_form\_default\_fields\_markup', 'wpd\_remove\_comment\_website\_field', 99 );

How to use code snippets to copy articles

The following code can add the copy function to WordPress articles / custom articles. The duplicate button will appear in the article list, but the copy function will not be added to the page. You can save one by using it Copy article function plug-in.

/*
 * Function for post duplication. Dups appear as drafts. User is redirected to the edit screen
 */
function rd\_duplicate\_post\_as\_draft(){
  global $wpdb;
  if (! ( isset( $\_GET\['post'\]) || isset( $\_POST\['post'\])  || ( isset($\_REQUEST\['action'\]) && 'rd\_duplicate\_post\_as\_draft' == $\_REQUEST\['action'\] ) ) ) {
    wp_die('No post to duplicate has been supplied!');
  }
 
  /*
   * Nonce verification
   */
  if ( !isset( $\_GET\['duplicate\_nonce'\] ) || !wp\_verify\_nonce( $\_GET\['duplicate\_nonce'\], basename( \_\_FILE\_\_ ) ) )
    return;
 
  /*
   * get the original post id
   */
  $post\_id = (isset($\_GET\['post'\]) ? absint( $\_GET\['post'\] ) : absint( $\_POST\['post'\] ) );
  /*
   * and all the original post data then
   */
  $post = get\_post( $post\_id );
 
  /*
   * if you don't want current user to be the new post author,
   * then change next couple of lines to this: $new\_post\_author = $post->post_author;
   */
  $current\_user = wp\_get\_current\_user();
  $new\_post\_author = $current_user->ID;
 
  /*
   * if post data exists, create the post duplicate
   */
  if (isset( $post ) && $post != null) {
 
    /*
     * new post data array
     */
    $args = array(
      'comment\_status' => $post->comment\_status,
      'ping\_status'    => $post->ping\_status,
      'post\_author'    => $new\_post_author,
      'post\_content'   => $post->post\_content,
      'post\_excerpt'   => $post->post\_excerpt,
      'post\_name'      => $post->post\_name,
      'post\_parent'    => $post->post\_parent,
      'post\_password'  => $post->post\_password,
      'post_status'    => 'draft',
      'post\_title'     => $post->post\_title,
      'post\_type'      => $post->post\_type,
      'to\_ping'        => $post->to\_ping,
      'menu\_order'     => $post->menu\_order
    );
 
    /*
     * insert the post by wp\_insert\_post() function
     */
    $new\_post\_id = wp\_insert\_post( $args );
 
    /*
     * get all current post terms ad set them to the new post draft
     */
    $taxonomies = get\_object\_taxonomies($post->post\_type); // returns array of taxonomy names for post type, ex array("category", "post\_tag");
    foreach ($taxonomies as $taxonomy) {
      $post\_terms = wp\_get\_object\_terms($post_id, $taxonomy, array('fields' => 'slugs'));
      wp\_set\_object\_terms($new\_post\_id, $post\_terms, $taxonomy, false);
    }
 
    /*
     * duplicate all post meta just in two SQL queries
     */
    $post\_meta\_infos = $wpdb->get\_results("SELECT meta\_key, meta\_value FROM $wpdb->postmeta WHERE post\_id=$post_id");
    if (count($post\_meta\_infos)!=0) {
      $sql\_query = "INSERT INTO $wpdb->postmeta (post\_id, meta\_key, meta\_value) ";
      foreach ($post\_meta\_infos as $meta_info) {
        $meta\_key = $meta\_info->meta_key;
        if( $meta\_key == '\_wp\_old\_slug' ) continue;
        $meta\_value = addslashes($meta\_info->meta_value);
        $sql\_query\_sel\[\]= "SELECT $new\_post\_id, '$meta\_key', '$meta\_value'";
      }
      $sql\_query.= implode(" UNION ALL ", $sql\_query_sel);
      $wpdb->query($sql_query);
    }
 
 
    /*
     * finally, redirect to the edit post screen for the new draft
     */
    wp\_redirect( admin\_url( 'post.php?action=edit&post=' . $new\_post\_id ) );
    exit;
  } else {
    wp\_die('Post creation failed, could not find original post: ' . $post\_id);
  }
}
add\_action( 'admin\_action\_rd\_duplicate\_post\_as\_draft', 'rd\_duplicate\_post\_as_draft' );
 
/*
 * Add the duplicate link to action list for post\_row\_actions
 */
function rd\_duplicate\_post_link( $actions, $post ) {
  if (current\_user\_can('edit_posts')) {
    $actions\['duplicate'\] = '<a href="' . wp\_nonce\_url('admin.php?action=rd\_duplicate\_post\_as\_draft&post=' . $post->ID, basename(\_\_FILE\_\_), 'duplicate_nonce' ) . '" title="Duplicate this item" rel="permalink">Duplicate</a>';
  }
  return $actions;
}
 
add\_filter( 'post\_row\_actions', 'rd\_duplicate\_post\_link', 10, 2 );

How to use code snippets to prevent WordPress from automatically generating pictures

When each picture is uploaded to WordPress, many pictures of different sizes will be automatically generated by WordPress or some plug-ins. For the unused picture size, you can directly organize the system to generate pictures with short code, which can not only save space, but also avoid consuming compression quota. The following describes how to use code snippets to prohibit WordPress from automatically generating pictures.

It is important to know that these automatically generated pictures cannot be seen in the media library of Wordpress and need to be viewed in the folder of the server.

The following figure is Siteground For the method of viewing picture files in the background, please operate in the order shown in the following figure after entering Sitetools of the website. We can see that the system has generated many pictures of different sizes for the same picture.

Before the website page is designed and the content is uploaded, we first prohibit all automatically generated images; If the content can be uploaded immediately, we can release the size of some pictures according to the design situation. For example, when making the product list page, we use 300*300px pictures, then in the following code, add / / comments in front of the corresponding line of code or delete the line directly.

// disable generated image sizes
function shapeSpace_disable_image_sizes($sizes) {
    
    unset($sizes['thumbnail']);    // disable thumbnail size
    unset($sizes['medium']);       // disable medium size
    unset($sizes['large']);        // disable large size
    unset($sizes['medium_large']); // disable medium-large size
    unset($sizes['1536x1536']);    // disable 2x medium-large size
    unset($sizes['2048x2048']);    // disable 2x large size
   unset($sizes['shop_catalog']);
   unset($sizes['shop_single']);
   unset($sizes['shop_thumbnail']);
   unset($sizes['woocommerce_thumbnail']);
   unset($sizes['woocommerce_single']);
   unset($sizes['woocommerce_gallery_thumbnail']);
    
    return $sizes;
    
}
add_action('intermediate_image_sizes_advanced', 'shapeSpace_disable_image_sizes');

// disable scaled image size
add_filter('big_image_size_threshold', '__return_false');

// disable other image sizes
function shapeSpace_disable_other_image_sizes() {
    
    remove_image_size('post-thumbnail'); // disable images added via set_post_thumbnail_size() 
    remove_image_size('another-size');   // disable any other added image sizes
    
}
add_action('init', 'shapeSpace_disable_other_image_sizes');

How to use code snippets to remove bread crumbs from the home page and list page of woocomerce products

/**
 * Remove the breadcrumbs 
 */
add\_action( 'init', 'woo\_remove\_wc\_breadcrumbs' );
function woo\_remove\_wc_breadcrumbs() {
    remove\_action( 'woocommerce\_before\_main\_content', 'woocommerce_breadcrumb', 20, 0 );
}

The original text of this article is written by LOYSEO Released, LOYSEO focuses on WordPress, Elementor and foreign trade website building tutorials.

Recommended reading

Foreign trade station building series tutorials
The ultimate course of B2B foreign trade station construction in 2020
What should we pay attention to when building a foreign trade station in 2020? (4300 words)

Tags: PHP

Posted by khayll on Mon, 16 May 2022 01:16:27 +0300