Một số đoạn code thông dụng dành cho wordpress

Trong quá trình bạn tùy chỉnh Website WordPress chắc hẳn bạn sẽ gặp khả nhiều vấn đề phát sinh do việc thiếu code, thiếu tính năng, hoặc có thể là do mẫu theme đó chưa có các đoạn code đó. Dưới đây là một số đoạn code thông dụng dành cho web wordpress mà Themewp đã sưu tầm và tổng hợp lại phần nào có thể giúp ích được cho bạn.

Một số đoạn code thông dụng dành cho wordpress

Code tự động lưu ảnh từ web khác về sever mình khi copy bài viết

class Auto_Save_Images{
 
    function __construct(){     
        
        add_filter( 'content_save_pre',array($this,'post_save_images') ); 
    }
    
    function post_save_images( $content ){
        if( ($_POST['save'] || $_POST['publish'] )){
            set_time_limit(240);
            global $post;
            $post_id=$post->ID;
            $preg=preg_match_all('/save_images($image_url,$post_id);
                        $replace=$res['url'];
                        $content=str_replace($image_url,$replace,$content);
                    }
                }
            }
        }
        remove_filter( 'content_save_pre', array( $this, 'post_save_images' ) );
        return $content;
    }
    
    function save_images($image_url,$post_id){
        $file=file_get_contents($image_url);
        $post = get_post($post_id);
        $posttitle = $post->post_title;
        $postname = sanitize_title($posttitle);
        $im_name = "$postname-$post_id.jpg";
        $res=wp_upload_bits($im_name,'',$file);
        $this->insert_attachment($res['file'],$post_id);
        return $res;
    }
    
    function insert_attachment($file,$id){
        $dirs=wp_upload_dir();
        $filetype=wp_check_filetype($file);
        $attachment=array(
            'guid'=>$dirs['baseurl'].'/'._wp_relative_upload_path($file),
            'post_mime_type'=>$filetype['type'],
            'post_title'=>preg_replace('/.[^.]+$/','',basename($file)),
            'post_content'=>'',
            'post_status'=>'inherit'
        );
        $attach_id=wp_insert_attachment($attachment,$file,$id);
        $attach_data=wp_generate_attachment_metadata($attach_id,$file);
        wp_update_attachment_metadata($attach_id,$attach_data);
        return $attach_id;
    }
}
new Auto_Save_Images();

Code chuyển sản phẩm không có giá thành “Liên hệ”

add_filter('woocommerce_empty_price_html', 'custom_call_for_price'); 
function custom_call_for_price() 
{ return 'Liên hệ'; }

Code bỏ nút “Thêm vào giỏ hàng”

remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
 remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );

Code bỏ phần đánh giá trong trang chi tiết giỏ hàng

//bỏ đánh giá 
add_filter( 'woocommerce_product_tabs', 'wcs_woo_remove_reviews_tab', 98 ); 
function wcs_woo_remove_reviews_tab($tabs) { unset($tabs['reviews']); return $tabs; }

Code dịch những từ cứng đầu trong WooCommerce

// Dịch woocommerce

function ra_change_translate_text( $translated_text ) {
if ( $translated_text == 'Old Text' ) {
$translated_text = 'New Translation';
}
return $translated_text;
}
add_filter( 'gettext', 'ra_change_translate_text', 20 );
function ra_change_translate_text_multiple( $translated ) {
$text = array(
'Continue Shopping' => 'Tiếp tục mua hàng',
'Update cart' => 'Cập nhật giỏ hàng',
'Apply Coupon' => 'Áp dụng mã ưu đãi',
'WooCommerce' => 'Quản lý bán hàng',

);
$translated = str_ireplace( array_keys($text), $text, $translated );
return $translated;
}
add_filter( 'gettext', 'ra_change_translate_text_multiple', 20 );
// End dich

Code thêm 1 Tab mới trong WooCommerce

    add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
    
    // Adds the new tab
    
    $tabs['test_tab'] = array(
        'title'     => __( 'Lịch trình chi tiết', 'woocommerce' ),
        'priority'  => 50,
        'callback'  => 'woo_new_product_tab_content'
    );

    return $tabs;

}
function woo_new_product_tab_content() {

    // The new tab content
   echo "Nôiị dung";
   
    
}

Code xóa đoạn slug featured_item trong Porfolio

function ah_remove_custom_post_type_slug( $post_link, $post, $leavename ) {
 
    if ( ! in_array( $post->post_type, array( 'featured_item' ) ) || 'publish' != $post->post_status )
        return $post_link;
 
    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
 
    return $post_link;
}
add_filter( 'post_type_link', 'ah_remove_custom_post_type_slug', 10, 3 );
 
function ah_parse_request_tricksy( $query ) {
    
    if ( ! $query->is_main_query() )
        return;
 
    if ( 2 != count( $query->query )
        || ! isset( $query->query['page'] ) )
        return;
 
    if ( ! empty( $query->query['name'] ) )
        $query->set( 'post_type', array( 'post', 'featured_item', 'page' ) );
}
add_action( 'pre_get_posts', 'ah_parse_request_tricksy' );

Đoạn code xóa Featured_item_category trong porfolio

add_filter('request', 'rudr_change_term_request', 1, 1 );
 
function rudr_change_term_request($query){
 
    $tax_name = 'featured_item_category'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'
 
    // Request for child terms differs, we should make an additional check
    if( $query['attachment'] ) :
        $include_children = true;
        $name = $query['attachment'];
    else:
        $include_children = false;
        $name = $query['name'];
    endif;
 
 
    $term = get_term_by('slug', $name, $tax_name); // get the current term to make sure it exists
 
    if (isset($name) && $term && !is_wp_error($term)): // check it here
 
        if( $include_children ) {
            unset($query['attachment']);
            $parent = $term->parent;
            while( $parent ) {
                $parent_term = get_term( $parent, $tax_name);
                $name = $parent_term->slug . '/' . $name;
                $parent = $parent_term->parent;
            }
        } else {
            unset($query['name']);
        }
 
        switch( $tax_name ):
            case 'category':{
                $query['category_name'] = $name; // for categories
                break;
            }
            case 'post_tag':{
                $query['tag'] = $name; // for post tags
                break;
            }
            default:{
                $query[$tax_name] = $name; // for another taxonomies
                break;
            }
        endswitch;
 
    endif;
 
    return $query;
 
}
 
 
add_filter( 'term_link', 'rudr_term_permalink', 10, 3 );
 
function rudr_term_permalink( $url, $term, $taxonomy ){
 
    $taxonomy_name = 'featured_item_category'; // your taxonomy name here
    $taxonomy_slug = 'featured_item_category'; // the taxonomy slug can be different with the taxonomy name (like 'post_tag' and 'tag' )
 
    // exit the function if taxonomy slug is not in URL
    if ( strpos($url, $taxonomy_slug) === FALSE || $taxonomy != $taxonomy_name ) return $url;
 
    $url = str_replace('/' . $taxonomy_slug, '', $url);
 
    return $url;
}

Code hiện tất cả category của 1 custom post type

 0 ) {
echo '

Total Projects: '. $count . '

'; echo '
    ‘;
    foreach ( $terms as $term ) {
    echo ‘

  • ‘;
    echo ‘Code hiện custom taxonomy của 1 product
    global $product;
    $terms = get_the_terms( $product->ID, 'thuong_hieu' );
      foreach($terms as $term) {
        echo 'Thương hiệu: '.$term->name.'';
      }

    Đoạn code thay dấu […] bằng … trong short description

    function new_excerpt_more( $excerpt ) {
        return str_replace( '[...]', '...', $excerpt );
    }
    add_filter( 'excerpt_more', 'new_excerpt_more' );

    Đoạn code bỏ luôn dấu […] Trong short Description (Bao gồm woocommerce)

    function new_excerpt_more( $more ) {
        return '';
    }
    add_filter('excerpt_more', 'new_excerpt_more');

    Đoạn Code để tìm kiếm mặc định có thể tìm kiếm được đoạn text trong custom field

    function cf_search_join( $join ) {
        global $wpdb;
    
        if ( is_search() ) {    
            $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
        }
    
        return $join;
    }
    add_filter('posts_join', 'cf_search_join' );
    
    /**
     * Modify the search query with posts_where
     *
     * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
     */
    function cf_search_where( $where ) {
        global $pagenow, $wpdb;
    
        if ( is_search() ) {
            $where = preg_replace(
                "/(s*".$wpdb->posts.".post_titles+LIKEs*('[^']+')s*)/",
                "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
        }
    
        return $where;
    }
    add_filter( 'posts_where', 'cf_search_where' );
    
    /**
     * Prevent duplicates
     *
     * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
     */
    function cf_search_distinct( $where ) {
        global $wpdb;
    
        if ( is_search() ) {
            return "DISTINCT";
        }
    
        return $where;
    }
    add_filter( 'posts_distinct', 'cf_search_distinct' );

    Tắt chức năng tìm kiếm content trong WordPress

    Đôi khi bạn cần tìm kiếm một từ khóa, nhưng kết quả tìm kiếm lại cho ra cả những bài viết có chứa từ khóa đó, trong khi đó bạn chỉ muốn tìm kiếm trong title. Vậy bạn copy đoạn code sau cho vào file functions.php là được.

    function __search_by_title_only( $search, &$wp_query )
    {
        global $wpdb;
        if ( empty( $search ) )
            return $search; // skip processing – no search term in query
        $q = $wp_query->query_vars;
        $n = ! empty( $q['exact'] ) ? '' : '%';
        $search =
        $searchand = '';
        foreach ( (array) $q['search_terms'] as $term ) {
            $term = esc_sql( like_escape( $term ) );
            $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
            $searchand = ' AND ';
        }
        if ( ! empty( $search ) ) {
            $search = " AND ({$search}) ";
            if ( ! is_user_logged_in() )
                $search .= " AND ($wpdb->posts.post_password = '') ";
        }
    return $search; } add_filter( 'posts_search', '__search_by_title_only', 500, 2 );

    Đoạn code thay đổi giá toàn bộ sản phẩm trong Woocommerce

    function update_products_sale_price(){
    
        $args = array(
            'posts_per_page' => -1,
            'post_type' => 'product',
            'post_status' => 'publish'
        );
    
        // getting all products
        $products = get_posts( $args );
    
        // Going through all products
        foreach ( $products as $key => $value ) {
    
            // the product ID
            $product_id = $value->ID;
    
            // Getting the product sale price
            $sale_price = get_post_meta($product_id, '_sale_price', true);
    
            // if product sale price is not defined we give to the variable a 0 value
            if (empty($sale_price))
                $sale_price = 0;
    
            // Getting the product sale price
            $price = get_post_meta($product_id, '_regular_price', true);
    
            // udate sale_price to 0 if sale price is bigger than price
            if ($sale_price < $price)
                update_post_meta($product_id, '_sale_price', '3500000');
               // Sua toan bộ giá của sale price thành 3500000. Sau đó tiếp tục chạy một lần nữa, thay _sale_price thành _regular_price để đổi giá gốc
        }
    }
    
    // Here the function we will do the job.
    update_products_sale_price();

    Cấu hình để giỏ hàng chỉ chấp nhận 1 sản phẩm cuối cùng thêm vào giỏ, nếu đã có sản phẩm trước đó thì remove sản phẩm đó đi và add sản phẩm mới vào

    // Removing on add to cart if an item is already in cart
    
    add_filter( ‘woocommerce_add_cart_item_data’, ‘remove_before_add_to_cart’ );
    
    function remove_before_add_to_cart( $cart_item_data ) {
    
        WC()->cart->empty_cart();
    
        return $cart_item_data;
    
    }
    
    // Removing one item on cart item check if there is more than 1 item in cart
    
    add_action( ‘template_redirect’, ‘checking_cart_items’ ); // Cart and Checkout
    
    function checking_cart_items() {
    
        if( sizeof( WC()->cart->get_cart() ) > 1 ){
    
            $cart_items_keys = array_keys(WC()->cart->get_cart());
    
            WC()->cart->remove_cart_item($cart_items_keys[0]);
    
        }
    
    }
    
    

    Code di chuyển giá của sản phẩm có biến thể lên đầu

    add_action( 'woocommerce_single_product_summary', 'move_single_product_variable_price_location', 2 );
    
    function move_single_product_variable_price_location() {
        global $product;
    
        // Variable product only
        if( $product->is_type('variable') ):
    
        // removing the price of variable products
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
    
        // Add back the relocated (customized) price of variable products
        add_action( 'woocommerce_single_product_summary', 'custom_single_product_variable_prices', 10 );
    
        endif;
    }
    
    
    function custom_single_product_variable_prices(){
        global $product;
    
        // Main Price
        $prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
        $price = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
    
        // Sale Price
        $prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
        sort( $prices );
        $saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
    
        if ( $price !== $saleprice && $product->is_on_sale() ) {
            $price = '' . $saleprice . $product->get_price_suffix() . ' ' . $price . $product->get_price_suffix() . '';
        }
    
        ?>
        
        
        '.$price.'
        
    '.$price.'
    '; }

    Code hiện custom field ở taxonomy

    add_action('woocommerce_after_main_content','thong_tin');
    function thong_tin(){
    
      $term = get_queried_object(); // lấy danh mục
        $content = get_field('bottom_content', $term);
    if(!empty($content)){
        echo $content;
    }
            
    
    }

     

    Một số code hay dành cho Theme WordPress Flatsome

    Thay chữ Tài khoản trên menu thành Xin chào, tên User:

    Vào file flatsometemplate-partsheaderpartialselement-account,tìm chữ My account và thay bằng đoạn code sau:

    user_lastname;
    
        printf( __( ‘Xin chào, %s’, ‘wpdance’ ), $user_last_name );
    
    } ?>

    Khắc phục lỗi lệch khung web khi có hiệu ứng trên mobile

    html, body {overflow-x: hidden;}

     

    Tăng độ dài của mô tả trong trang Category Post

    Vào đường dẫn themes/flatsome/template-parts/posts/archive-list.php, thêm dòng excerpt_length=”100″ vào trong đoạn shortcode. có thể thay đổi số 100 thành số khác để tùy biến độ dài.

    Chuyển thuộc tính của sản phẩm từ dưới Tab Thông tin bổ sung lên phía dưới nút Add To Cart

    // Xóa thông tin bổ sung ở dưới tab
    
    add_filter( ‘woocommerce_product_tabs’, ‘remove_additional_information_tab’, 100, 1 );
    
    function remove_additional_information_tab( $tabs ) {
    
        unset($tabs[‘additional_information’]);
    
        return $tabs;
    
    }
    
    // Thêm thông tin bổ sung phía dưới nút Add to Cart
    
    add_action( ‘woocommerce_single_product_summary’, ‘additional_info_under_add_to_cart’, 35 );
    
    function additional_info_under_add_to_cart() {
    
        global $product;
    
        if ( $product && ( $product->has_attributes() || apply_filters( ‘wc_product_enable_dimensions_display’, $product->has_weight() || $product->has_dimensions() ) ) ) {
    
            wc_display_product_attributes( $product );
    
        }
    
    }

    Gọi mô tả của danh mục sản phẩm ra ngoài

    add_action( ‘woocommerce_after_subcategory_title’, ‘woovn_add_product_description’, 12);
    
    function woovn_add_product_description ($category) {
    
    $cat_id = $category->term_id;
    
    $prod_term = get_term($cat_id,’product_cat’);
    
    $description= $prod_term->description;
    
    echo ‘

    ’.$description.'

    ’; ?>

    Tắt Responsive cho theme Flatsome

    Responsive là một-thứ-gì-đó kỳ diệu mà HTML cùng CSS mang lại cho người dùng. Tuy nhiên, trong một số trường hợp bạn không “thích” nó mà dùng cách khác thì chỉ cần chèn đoạn mã này vào file function.phpcủa theme bạn đang dùng là xong

    add_action('init' , 'disable_flatsome_viewport_meta' , 15 );
    function disable_flatsome_viewport_meta() {
    remove_action( 'wp_head', 'flatsome_viewport_meta', 1 );
    }

    Cách ẩn thông báo đăng ký flatsome

     add_action( 'init', 'hide_notice' );
    function hide_notice() {
       remove_action( 'admin_notices', 'flatsome_maintenance_admin_notice' );
    }

    Ngăn các Block trong UX Builder tạo html khi chọn hidden

    // Ngăn UXBuilder tự tạo html kể cả khi chọn visible hidden
    add_filter( 'do_shortcode_tag', 'add_filter_shortcode_ux_visibility', 10, 3 );
    function add_filter_shortcode_ux_visibility( $output, $tag, $attr ) {
        if( !isset($attr['visibility']) )
            return $output;
        
        if($attr['visibility'] == 'hidden')
            return;
        
        if( ($attr['visibility'] == 'hide-for-medium') &&  wp_is_mobile() ) 
            return;
        elseif( ($attr['visibility'] == 'show-for-small') && !wp_is_mobile() ) 
            return;
        elseif( ($attr['visibility'] == 'show-for-medium') && !wp_is_mobile() )
            return;
        elseif( ($attr['visibility'] == 'hide-for-small') && wp_is_mobile() )
            return;
        
        return $output;
    }

    Thêm text tùy chọn vào sau giá

    add_filter( 'woocommerce_get_price_html', 'devvn_price_prefix_suffix', 99, 2 );
    function devvn_price_prefix_suffix( $price, $product ){
        if(is_singular('product')) {
            $price = $price . '(Chưa bao gồm VAT)';
        }
        return apply_filters( 'woocommerce_get_price', $price );
    }

    Cách sử dụng các đoạn code trên

    Rất đơn giản để sử dụng các đoạn code trên bạn vào file funtions.php của theme đang dùng copy đoạn code cần sử dụng vào và lưu tại kiểm tra kết quả.
    Bạn nên copy file funtions.php của theme gốc qua child theme để chỉnh sửa cho an toàn, để không bị mất code khi update theme.

     

     

    5/5 - (6 bình chọn)

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Trở lại
Zalo
Hotline
Facebook
Chat Messenger
Telegram
Email