10个WordPress建站常用代码段(Code Snippets)

标题缩短

运用代码段(Code Snippets)插件管理代码,可以不用额外安装更多插件,来解决WordPress建站过程中的一些常见功能需求,譬如安装Google analytics跟踪代码。下文中记录了我在外贸建站和个人博客中常用到的代码段。

如何禁用WordPress的XML-RPC

WordPress站点很少需要启用XML-RPC,但是启用它可能会导致大量的安全问题。如果你使用WordPress应用程序,你才需要启用它。此代码片段将禁用XML-RPC以提高站点安全性。

add_filter('xmlrpc_enabled', '__return_false');

如何用代码段安装Google Analytics跟踪代码

将从Google analytics中获取的跟踪代码放入到如下代码段中

add_action( 'wp_head', function () { ?> 这里粘贴Google Analytics的跟踪代码 <?php });

如何移除/隐藏WordPress评论中的Url字段

下面这段代码可以移除/隐藏部分WordPress主题中评论URL字段,如果你使用后发现不能移除,那说明主题不兼容,你可以在谷歌搜索:Remove Website field from the Comment Form in XXX theme,将XXX改为你的主题名称。

function remove_comment_fields($fields) {
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');

譬如,在astra主题免费版中,隐藏评论的url字段使用下面的代码

function wpd_remove_comment_website_field( $fields ) {
    unset( $fields['url'] );
    
    return $fields;
}
add_filter( 'comment_form_default_fields', 'wpd_remove_comment_website_field', 99 );

在astra 主题付费版中,移除评论的url字段使用下面的代码

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 );

如何用代码段实现复制文章功能

下面这段代码可以给WordPress文章/自定义文章添加复制功能,在文章列表中会出现duplicate按钮,但不会给页面添加复制功能。

/*
 * 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 title="Duplicate this item" href="' . wp_nonce_url('admin.php?action=rd_duplicate_post_as_draft&post=' . $post->ID, basename(__FILE__), 'duplicate_nonce' ) . '" rel="permalink">Duplicate';
  }
  return $actions;
}
 
add_filter( 'post_row_actions', 'rd_duplicate_post_link', 10, 2 );

如何用代码段禁止WordPress自动生成图片

由于每张图片在上传到WordPress时,会被WordPress或部分插件自动生成很多不同尺寸的图片,针对用不上的图片尺寸,可以用短代码直接组织系统生成图片,不仅能节省空间,也能避免消耗压缩额度,下面介绍如何用代码段(code snippets)禁止WordPress自动生成图片。

需要知道的是,这些自动生成的图片并不能在Wordpress的媒体库看到,需要在服务器的文件夹中查看。

下图是宝塔面板后台查看图片文件的方法,请在进入网站的文件管理页面操作查看,我们能看到系统为同一张图生成了很多不同尺寸的图片。

宝塔文件管理页面

在网站页面设计完、内容上传前,我们先禁止所有自动生成的图片;若马上可以上传内容了,我们可以根据设计情况,酌情放开部分图片尺寸,譬如在制作产品列表页时,我们用到了300*300px的图片,那么就在下面的代码中,将对应行的代码前加//注释掉或直接删除该行。

// 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');

如何用代码段去掉Woocommerce产品首页、列表页的面包屑

/**
 * 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 );
}

WooCommerce如何在付款后自动完成虚拟订单

add_filter( 'woocommerce_payment_complete_order_status', 'wmg_auto_complete_virtual_orders', 10, 3 );

/**
 * Automatically complete orders with only virtual products
 *
 * @param  string   $payment_complete_status Order status used after an order payment is received
 * @param  int      $order_id                ID of the order being processed
 * @param  WC_Order $order                   Order object being processed
 * @return string   $payment_complete_status Updated order status
 */
function wmg_auto_complete_virtual_orders( $payment_complete_status, $order_id, $order ) {
  $current_status = $order->get_status();
  // We only want to update the status to 'completed' if it's coming from one of the following statuses: 
  $allowed_current_statuses = array( 'on-hold', 'pending', 'failed' );

  if ( 'processing' === $payment_complete_status && in_array( $current_status, $allowed_current_statuses ) ) {

    $order_items = $order->get_items();

    // Create an array of products in the order
    $order_products = array_filter( array_map( function( $item ) {
      // Get associated product for each line item
      return $item->get_product();
    }, $order_items ), function( $product ) {
      // Remove non-products
      return !! $product;
    } );

    if ( count( $order_products > 0 ) ) {
      // Check if each product is 'virtual'
      $is_virtual_order = array_reduce( $order_products, function( $virtual_order_so_far, $product ) {
        return $virtual_order_so_far && $product->is_virtual();
      }, true );

      if ( $is_virtual_order ) {
        $payment_complete_status = 'completed';
      }
    }

  }

  return $payment_complete_status;
}

如何将Woocomerce产品列表页的“Add To Cart”按钮替换为查看产品详情按钮

woocommerce移除加入购物车按钮

add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
function replacing_add_to_cart_button( $button, $product  ) {
    $button_text = __("Add to quote", "woocommerce");
    $button = '< a class="button" href="' . $product->get_permalink() . '">' . $button_text . '';

    return $button;
}

如果你想修改按钮上的文案,将上述代码中的“Add to quote”对应改掉即可。这个还可以参考以下方法:外贸独立站删除和隐藏WooCommerce添加到购物车按钮的几种方式

如何缩短WooCommerce产品列表中的产品标题的字符数

标题缩短

// Automatically shortens WooCommerce product titles on the main shop, category, and tag pages
// to a set number of characters 
function short_woocommerce_product_titles_chars( $title, $id ) {
  if ( ( is_shop() || is_product_tag() || is_product_category() ) && get_post_type( $id ) === 'product' ) {
    // Kicks in if the product title is longer than 32 characters 
    if ( strlen( $title ) > 30) {
      // Shortens it to 32 characters and adds ellipsis at the end
      return substr( $title, 0, 32 ) . '...';
    }
  }

  return $title;
}
add_filter( 'the_title', 'short_woocommerce_product_titles_chars', 10, 2 ); 

在上面的代码中,数字30表示:你希望标题展示的字符数量,你可以按需调整这个数值,标题超长部分以…显示。

WordPress文章/页面上禁止加载WooCommerce .Js(Javascript)和.Css文件?

woocommerce会在每个页面都默认加载几个css和js,这对网站速度是有影响的,将下面这段代码,能够实现在除了购物车、结算、账户、产品以外的页面中,移除woocommerce的css和js。

/** 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() && ! is_account_page() ) {
# 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' );
}
}
}

如果报错,可以把代码中的dequeue_woocommerce_styles_scripts改为dequeue_woocommerce_styles_script。

类似文章