WP 实用代码集

禁止自动更新和更新提示

在当前主题的 function.php 结束位置添加:

add_filter('pre_site_transient_update_core', create_function('$a', "return null;")); // 关闭核心提示  
add_filter('pre_site_transient_update_plugins', create_function('$a', "return null;")); // 关闭插件提示  
add_filter('pre_site_transient_update_themes', create_function('$a', "return null;")); // 关闭主题提示  
remove_action('admin_init', '_maybe_update_core'); // 禁止 WordPress 检查更新  
remove_action('admin_init', '_maybe_update_plugins'); // 禁止 WordPress 更新插件  
remove_action('admin_init', '_maybe_update_themes'); // 禁止 WordPress 更新主题

在 wp-config.php 添加如下代码:

define( 'AUTOMATIC_UPDATER_DISABLED', true );

列表页显示评论数量

结算页显示产品缩略图

/**
 * @snippet       Woocommerce结算页订单添加产品缩略图
 */

add_filter( 'woocommerce_cart_item_name', 'ts_product_image_on_checkout', 10, 3 );

function ts_product_image_on_checkout( $name, $cart_item, $cart_item_key ) {

    /* Return if not checkout page */
    if ( ! is_checkout() ) {
        return $name;
    }

    /* Get product object */
    $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

    /* Get product thumbnail */
    $thumbnail = $_product->get_image();

    /* Add wrapper to image and add some css */
    $image = '
' . $thumbnail . '
'; /* Prepend image to name and return it */ return $image . $name; }

添加随机排序

function custom_woocommerce_get_catalog_ordering_args( $args ) {
    $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'random_list' == $orderby_value ) {
        $args['orderby'] = 'rand';
        $args['order'] = '';
        $args['meta_key'] = '';
    }
    return $args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['random_list'] = __('Sort by random order');
    return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );

为订单添加手续费

add_action( 'woocommerce_calculate_totals','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
    global $woocommerce;
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    $percentage = 0.01;
    $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
    $woocommerce->cart->add_fee( 'Surcharge', $surcharge, false, '' );
    $woocommerce->cart->fee_total += $surcharge;
}

付款成功后,立即发送invoice

/**
 * send invoice straight away if payment is successful
 * @param  string $order_id valid payment order id
 * @return null
 */
function send_invoice_upon_payment_successful($order_id) {
  global $woocommerce;
  $order = new WC_Order($order_id);
  $mailer = $woocommerce->mailer();
  $mailer->customer_invoice( $order );
}
add_action('woocommerce_payment_complete', 'send_invoice_upon_payment_successful');

产品页添加自定义选项卡

//Add custom tab
add_filter( 'woocommerce_product_tabs', 'wc_add_features_tab' );
function wc_add_features_tab( $tabs ){   
    global $product;
    $content = get_post_meta( $product->id, 'product_features', true );
    if( !empty($content) ) {
        $tabs[ 'features' ] = array(
            'title'    => 'Features',
            'priority' => 1,
            'callback' => 'wc_features_tabs_panel_content',
            'content'  => $content,  // custom field
        );
    }
    return $tabs;
}
function wc_features_tabs_panel_content( $key, $tab ){
    echo  '

' . $tab['title'] . '

'; echo $tab['content']; }

用户访问时自动将产品添加至购物车

// add item to cart on visit
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
    if (!is_admin()) {
        global $woocommerce;
        $product_id = 64;
        $found = false;
        //check if product already in cart
        if (sizeof($woocommerce->cart->get_cart()) > 0) {
            foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) {
                $_product = $values['data'];
                if ($_product->id == $product_id)
                    $found = true;
            }
        // if product not found, add it
            if (!$found)
                $woocommerce->cart->add_to_cart($product_id);
        } else {
        // if no products in cart, add it
            $woocommerce->cart->add_to_cart($product_id);
        }
    }
}

列表页产品置顶

function wild_posts_results($posts){
    global $wpdb;
    if(!empty($_GET['sort_by_name'])){
        $skuArr= explode( ',', $_GET['sort_by_name']);
        $skuArr = array_reverse($skuArr);
        $ids = [];
        foreach($posts as $obj){
            $ids[]=$obj->ID;
        }
        foreach($skuArr as $sku){
            if(!empty($sku)){
                $post =  $wpdb->get_results( sprintf("SELECT * FROM  $wpdb->posts WHERE  post_type = '%s'  AND post_name = '%s'" , 'product', $sku ));
                if(empty($post)){
                    continue;
                }
                $post = $post[0];
                if($key = array_search($post->ID,$ids)){
                    unset($posts[$key]);
                }
                array_unshift($posts,$post);
            }
        }
        $posts = array_values($posts);
    }
    return $posts;
  }
  add_filter('posts_results',"wild_posts_results");

购物车自动更新产品数量

add_action( 'woocommerce_single_product_summary', 'woocommerce_total_product_price', 31 );
function woocommerce_total_product_price() {
    global $woocommerce, $product;

    echo sprintf('
%s %s
',__('Product Total:','woocommerce'),''.$product->get_price().''); echo sprintf('
%s %s
',__('Cart Total:','woocommerce'),''.$product->get_price().''); ?> jQuery(function($){ var price = get_price(); ?>, current_cart_total = cart->cart_contents_total; ?>, currency = ''; $('[name=quantity]').change(function(){ if (!(this.value < 1)) { var product_total = parseFloat(price * this.value), cart_total = parseFloat(product_total + current_cart_total); $('#product_total_price .price').html( currency + product_total.toFixed(2)); $('#cart_total_price .price').html( currency + cart_total.toFixed(2)); } $('#product_total_price,#cart_total_price').toggle(!(this.value <= 1)); }); }); <?php }

修改默认tab标题名和排序

add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
// Adds the new tab
$tabs['description']['title'] = __( '商品描述' );
$tabs['reviews']['title'] = __( '商品评价' );
$tabs['additional_information']['title'] = __( '商品参数' );
return $tabs;
}

修改排序
add_filter( 'woocommerce_product_tabs', 'sb_woo_move_description_tab', 98); function sb_woo_move_description_tab($tabs) { $tabs['description']['priority'] = 5;
$tabs['additional_information']['priority']=10;
$tabs['reviews']['priority'] = 20; return $tabs;
return $tabs;
}

新增tab
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
// Adds the new tab
$tabs['desc_tab'] = array(
'title' => __( 'Additional Information', 'woocommerce' ),
'priority' => 50,
'callback' => 'woo_new_product_tab_content'
);
}

添加svg支持

add_filter('wp_check_filetype_and_ext', function ($data, $file, $filename, $mimes)
{
    global $wp_version;

    if ($wp_version !== '4.7.1') {
        return $data;
    }

    $filetype = wp_check_filetype($filename, $mimes);

    return [
        'ext'             => $filetype[ 'ext' ],
        'type'            => $filetype[ 'type' ],
        'proper_filename' => $data[ 'proper_filename' ],
    ];

}, 10, 4);

add_filter('upload_mimes', function ($mimes)
{
    $mimes[ 'svg' ] = 'image/svg+xml';

    return $mimes;
});

add_action('admin_head', function ()
{
    echo '
        .attachment-266x266, .thumbnail img {
             width: 100% !important;
             height: auto !important;
        }
        ';
});

关闭用户注册邮件通知

// 关闭用户注册时发送给管理员的电子邮件
add_filter( 'wp_new_user_notification_email_admin', '__return_false' );
// 关闭用户注册时发送给注册者的电子邮件
add_filter( 'wp_new_user_notification_email', '__return_false' );

关闭修改密码、重置密码的邮件通知

// 关闭 更改密码时发送给注册者的电子邮件
add_filter( 'send_password_change_email', '__return_false' );

// 关闭 重置密码时发送给管理员的电子邮件
add_filter( 'wp_password_change_notification_email', '__return_false' );
//禁止用户密码重置
apply_filters( 'allow_password_reset', '__return_false' );

添加立即购买按钮

/*添加buy now*/

add_action('woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );
add_action('woocommerce_after_add_to_cart_form', 'buy_now_submit_form');
add_filter('woocommerce_add_to_cart_redirect', 'redirect_to_checkout');

function add_content_after_addtocart() {
    // get the current post/product ID
    $current_product_id = get_the_ID();
    // get the product based on the ID
    $product = wc_get_product( $current_product_id );
    // get the "Checkout Page" URL
    //$checkout_url = wc_get_checkout_url();

    if (in_array($product->get_type(), ['simple', 'variable'])) {
        $buy_now_button = '

                          ';
        echo $buy_now_button;
    }
}

/**
 * 控制跳转
 */
function buy_now_submit_form() {
    ?>

        jQuery(document).ready(function(){
            // listen if someone clicks 'Buy Now' button
            jQuery('#buy_now_button').click(function(){
                // set value to 1
                jQuery('#is_buy_now').val('1');
                //submit the form
                jQuery('form.cart').submit();
            });
        });

    <?php
}

/**
 * 商品加入购物车后,返回要跳转的地址
 * @param $redirect_url
 * @return string
 */
function redirect_to_checkout($redirect_url) {
    if (isset($_REQUEST['is_buy_now']) && $_REQUEST['is_buy_now']) {
        $redirect_url = wc_get_checkout_url();
    }

    return $redirect_url;
}