運用代碼段(Code Snippets)外掛管理代碼,可以不用額外安裝更多外掛,來解決WordPress架設網站過程中的一些常見功能需求,譬如安裝Google analytics跟蹤代碼。 下文中記錄了我在外貿架設網站和個人博客中常用到的代碼段。
如何在WordPress文章/頁面上禁止載入WooCommerce .js(javascript)和.css檔?
woocommerce會在每個頁面都默認載入幾個css和js,這對網站速度是有影響的,將下面這段代碼,在code snippets外掛程式中添加一個新snippet,能夠實現在除了購物車、結算、帳戶、產品以外的頁面中,移除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' );
}
}
}
20201202更新:有讀者反饋提交時報錯:
The snippet has been deactivated due to an error on line 4: Cannot redeclare function dequeue_woocommerce_styles_scripts.
如果報錯,可以把代碼中的dequeue_woocommerce_styles_scripts改為dequeue_woocommerce_styles_script。 如果不報錯就不改。
如何禁用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網站安裝Google Analytics跟蹤代碼
如何移除/隱藏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 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 );
如何用代碼段禁止WordPress自動生成圖片
由於每張圖片在上傳到WordPress時,會被WordPress或部分外掛程式自動生成很多不同尺寸的圖片,針對用不上的圖片尺寸,可以用短代碼直接組織系統生成圖片,不僅能節省空間,也能避免消耗壓縮額度,下面介紹如何用代碼段(code snippets)禁止WordPress自動生成圖片。
需要知道的是,這些自動生成的圖片並不能在Wordpress的媒體庫看到,需要在伺服器的資料夾中查看。
下圖是Siteground後台查看圖片檔的方法,請在進入網站的Sitetools后按下圖所示順序操作查看,我們能看到系統為同一張圖生成了很多不同尺寸的圖片。
在網站頁面設計完、內容上傳前,我們先禁止所有自動生成的圖片; 若馬上可以上傳內容了,我們可以根據設計情況,酌情放開部分圖片尺寸,譬如在製作產品列表頁時,我們用到了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”按鈕替換為查看產品詳情按鈕
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 = __("View product", "woocommerce");
$button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
return $button;
}
如果你想修改按鈕上的文案,將上述代碼中的view product對應改掉即可。
如何縮短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 ) > 32) {
// 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 );
在上面的代碼中,數位32表示:你希望標題展示的字元數量,你可以按需調整這個數值。