運用代碼段(Code Snippets)插件管理代碼,可以不用額外安裝更多插件,來解決WordPress建站過程中的一些常見功能需求,譬如安裝Google analytics跟蹤代碼。下文中記錄了我在搭建外貿網站和個人博客中常用到的代碼段。
原文首發於:https://loyseo.com/code-snippets-for-wordpress/
如何在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() ) {
# 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' );
}
}
}
如何禁用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 );
}
本文原文由LOYSEO 發布,LOYSEO專注於WordPress、Elementor、外貿建站教程。