Full width home advertisement

IT Sharing

Travel the world

Climb the mountains

Post Page Advertisement [Top]


 

Khi bạn lập trình web wordpress chắc hẳn bạn sẽ gặp phải một số vấn đề phát sinh do việc thiếu code, hoặc code sai không chạy, hoặc có thể là do mẫu theme đó chưa có các đoạn code đó. Nếu trường hợp chưa có code thì các bạn có thể theo dõi một số đoạn code phổ biến dành cho web wordpress mà T2D Solution tổng hợp được dưới đây.

Một số đoạn code phổ biến dành cho wordpress

Dưới đây là một số đoạn code phổ biến dành cho lập trình thiết kế web wordpress

Code tự động lưu ảnh từ web khác về sever mình

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(‘/<img.*?src=”(.*?)”/’,stripslashes($content),$matches);

            if($preg){

                foreach($matches[1] as $image_url){

                    if(empty($image_url)) continue;

                    $pos=strpos($image_url,$_SERVER[‘HTTP_HOST’]);

                    if($pos===false){

                        $res=$this->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 nếu sản phẩm không có giá sẽ hiển thị Liên hệ

add_filter(‘woocommerce_empty_price_html’, ‘custom_call_for_price’);

function custom_call_for_price() {

return ‘<span class=”lien-he-price”>Liên hệ</span>’;

}

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

//Loại 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 Woocormerce

// 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 Woocormerce

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

<?php

$terms = get_terms( ‘nameofyourregisteredtaxonomygoeshere’ );

$count = count( $terms );

if ( $count > 0 ) {

echo ‘<h3>Total Projects: ‘. $count . ‘</h3>’;

echo ‘<ul>’;

foreach ( $terms as $term ) {

    echo ‘<li>’;

    echo ‘<a href=”‘ . esc_url( get_term_link( $term ) ) . ‘” alt=”‘. esc_attr( sprintf( __( ‘View all post filed under %s’, ‘my_localization_domain’ ), $term->name ) ) . ‘”>’ . $term->name . ‘</a>’;

    echo ‘</li>’;

}

echo ‘</ul>’;

}

?>

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: <a href=”‘.get_site_url().’/thuong_hieu/’.$term->slug.'”>’.$term->name.'</a>’;

    }

Đ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_title\s+LIKE\s*(\'[^\’]+\’)\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 = ‘<del>’ . $saleprice . $product->get_price_suffix() . ‘</del> <ins>’ . $price . $product->get_price_suffix() . ‘</ins>’;

    }

    ?>

    <style>

        div.woocommerce-variation-price,

        div.woocommerce-variation-availability,

        div.hidden-variable-price {

            height: 0px !important;

            overflow:hidden;

            position:relative;

            line-height: 0px !important;

            font-size: 0% !important;

            visibility: hidden !important;

        }

    </style>

    <script>

        jQuery(document).ready(function($) {

            // When variable price is selected by default

            setTimeout( function(){

                if( 0 < $(‘input.variation_id’).val() && null != $(‘input.variation_id’).val() ){

                    if($(‘p.availability’))

                        $(‘p.availability’).remove();

                    $(‘p.price’).html($(‘div.woocommerce-variation-price > span.price’).html()).append(‘<p class=”availability”>’+$(‘div.woocommerce-variation-availability’).html()+'</p>’);

                    console.log($(‘div.woocommerce-variation-availability’).html());

                }

            }, 300 );

            // On live variation selection

            $(‘select’).blur( function(){

                if( 0 < $(‘input.variation_id’).val() && null != $(‘input.variation_id’).val() ){

                    if($(‘.price p.availability’) || $(‘.price p.stock’) )

                        $(‘p.price p’).each(function() {

                            $(this).remove();

                        });

                    $(‘p.price’).html($(‘div.woocommerce-variation-price > span.price’).html()).append(‘<p class=”availability”>’+$(‘div.woocommerce-variation-availability’).html()+'</p>’);

                    console.log($(‘input.variation_id’).val());

                } else {

                    $(‘p.price’).html($(‘div.hidden-variable-price’).html());

                    if($(‘p.availability’))

                        $(‘p.availability’).remove();

                    console.log(‘NULL’);

                }

            });

        });

    </script>

    <?php

    echo ‘<p class=”price”>’.$price.'</p>

    <div class=”hidden-variable-price” >’.$price.'</div>’;

}

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 flatsome\template-parts\header\partials\element-account,tìm chữ My account và thay bằng đoạn code sau:

<?php if ( is_user_logged_in() ) {

    $user_info = wp_get_current_user();

    $user_last_name = $user_info->user_lastname;

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

} ?>

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.

Khắc phục tình trạng bị giật giật khi chỉnh sửa trong UX Builder

Bỏ code sau vào file functions.php

<?php // Do not include this if already open!

/**

 * Code goes in theme functions.php

 *

 * Temporary fix Chrome 66 frame glitch in UX Builder.

 */

add_action( ‘admin_head’, function () {

            ?>

            <style type=”text/css”>

                        .iframe-frame {

                                    box-shadow: unset !important;

                        }

            </style>

            <?php

} );

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

Thêm dòng này vào file style.css:

html, body {overflow-x: hidden;}

Khắc phục lỗi Editor hay sinh ra thẻ <p> rỗng

<script>

            jQuery(document).ready(function(){

jQuery(‘p’).each(function() {

 var $this = jQuery(this);

 if($this.html().replace(/\s|&nbsp;/g, ”).length == 0)

     $this.remove(); });

});

</script>

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 ‘<p>’.$description.'</p>’;

?>

<button href=”<?php echo get_the_permalink(); ?>” class=”button mb-0″>

                            <?php _e( ‘Read more’, ‘woocommerce’ ); ?>

                        </button>

<?php

}

?>


Change portfolio slug

/*

* Change slug of protfilio*/

add_filter( 'register_taxonomy_args', 't2ds_portfolio_type_args', 10, 2 );

function t2ds_portfolio_type_args( $args, $taxonomy ) {

if ( 'featured_item_category' === $taxonomy ) {

$args['rewrite']['slug'] = 'loai-du-an';

}


return $args;

}

Nguồn: Tổng hợp

Trên đây là một số đoạn code phổ biến trong lập trình web wordpressT2D Solution xin chào và hẹn gặp lại các bạn ở những bài viết sau.

Không có nhận xét nào:

Đăng nhận xét

Bottom Ad [Post Page]