WP 实用代码集

实用技巧 杨海雄 3周前 (04-21) 105次浏览 0个评论
文章目录[隐藏]

禁止自动更新和更新提示

在当前主题的 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() ) {
        returnname;
    }

    /* 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');
    returnsortby;
}
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 ){      globalproduct;
    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() ascart_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 itwoocommerce->cart->add_to_cart($product_id);
        }
    }
}

列表页产品置顶

function wild_posts_results(posts){
    globalwpdb;
    if(!empty(_GET['sort_by_name'])){skuArr= explode( ',', _GET['sort_by_name']);skuArr = array_reverse(skuArr);ids = [];
        foreach(posts asobj){
            ids[]=obj->ID;
        }
        foreach(skuArr assku){
            if(!empty(sku)){post =  wpdb->get_results( sprintf("SELECT * FROMwpdb->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);
    }
    returnposts;
  }
  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('',__('Product Total:','woocommerce'),''.$product->get_price().'');
    echo sprintf('',__('Cart Total:','woocommerce'),''.$product->get_price().'');
    ?>
        
    

修改默认 tab 标题名和排序

add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( tabs ) {
// Adds the new tabtabs['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; returntabs;
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 '';
});

关闭用户注册邮件通知

// 关闭用户注册时发送给管理员的电子邮件
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 IDproduct = 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() {
    ?>
    
    

杨海雄 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:WP 实用代码集
喜欢 (0)

您必须 登录 才能发表评论!