Những đoạn code hay dùng trong lập trình theme wordpress

Đây là những đoạn code hay dùng nhất và hay gặp nhất trong lập trình theme wordpress mà mình đã sưu tầm và tổng hợp, các bạn chỉ cần copy và dán vào thì nó hoạt động tốt nhé. Trước mắt hiểu hay không các đoạn code thì copy vào đã tính sau nhé :)).

1. Get post mặt định ( Lấy bài viết mặt định )

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
// viết code cần hiễn thị
<?php endwhile; else : ?>
<?php endif; ?>

Đặt code này ở file index.php thì sẽ lấy tất cả bài biết mới nhất nha, đặt ở file category.php thì sẽ lấy theo category và một kiểu mình hay làm nửa là đặt nó ở file single.php thì nó sẽ lấy nội dung bài viết ra nhé.

2. Lấy ID chuyên mục

Ở page single.php

$category = get_the_category();
$nameCate = $category[0]->cat_name;
$slugCate = $category[0]->slug;

Ở page category.php

$cate = get_queried_object();
$cateName = $cate->name;

Ở page index.php

<?php echo get_the_category( $id )[0]->name; ?>

Việc lấy name theo category thì rất cần thiết, hiễn thị ở breadcrum, hay bạn mún hiễn thị bài viết mà có thêm các chuyên mục đi kèm. Với khách hàng của mình thì lúc nào củng cần cả. Mọi người tham khảo rồi làm theo nha.

3. Code lấy bài viết mới nhất theo category

<?php $getposts = new WP_query(array( 
'post_type' => 'post', 
'pos_status' => 'publish', 
'posts_per_page' => 8, 
'cat' => 1 )); 
?>
<?php while ($getposts->have_posts()) : $getposts->the_post(); ?> // code cần hiễn thị <?php 
<?php endwhile; wp_reset_postdata(); ?>
  • posts_per_page: số lượng bài viết
  • cat: id của category đó. Và có thêm một cách viết nửa là category_name => ‘tên category’

4. Code lấy tất cả danh sách chuyên mục

<ul>
    <?php $args = array(
    'hide_empty' => 0,
    'taxonomy' => 'category',
    );
    $cates = get_categories( $args );
    foreach ( $cates as $cate ) { ?>
        <li>
            <a href="<?php echo get_term_link($cate->slug, 'category'); ?>">
            <?php echo $cate->name ?> (<?php echo $cate->count ?>)</a>
        </li>
    <?php } ?>
</ul>

5. Code phân trang

<!-- paginate -->
<?php if(paginate_links()!='') {
    ?>
        <div class="tvc_paginate">
            <?php
                global $wp_query;
                $big = 999999999;
                echo paginate_links( array(
                    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
                    'format' => '?paged=%#%',
                    'prev_text' => __('«'),
                    'next_text' => __('»'),
                    'current' => max( 1, get_query_var('paged') ),
                    'total' => $wp_query->max_num_pages
                ) );
            ?>
        </div>
        <?php 
    } 
?>

Đoạn code này thường đặt ở dưới nằm chung page với đoạn code get mặt định ở số 1 nha mọi người. Nếu đoạn code này mà bỏ vào không nằm chung với đoạn số 1 thì nó không nhận đâu. Thường thì mình sẽ làm phân trang ở trang chủ hoặc trang chuyên mục. Các bạn thao khảo làm theo nhé, cực kì hiệu quả nha.

Tiếp theo mình củng sẽ giới thiệu một đoạn code phân trang khác. Mình ví dụ lấy phân trang cho category.php

Full code cho phân trang

global $wp_query, $wp;
$termId = $wp_query->get_queried_object_id();
$posts_per_page = 9;
$currentPage = $_GET['page'] ?? 1;
get_header();
echo do_shortcode("[hfe_template id='2955']");
$currentPage = $_GET['page'] ?? 1;
$query = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $posts_per_page,
'paged' => $currentPage,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $termId
),
)
));
$maxPage = $query->max_num_pages;
if ( $query->have_posts() ) { ?>
<div class="category__container">
   <?php while ( $query->have_posts() ) {
      $query->the_post(); ?>
   <article class="category__article" data-id="<?php echo get_the_ID() ?>">
      // Nội dung cần hiễn thị
   </article>
   <?php } ?>
   <div class="category__pagination">
      <?php if ($currentPage > 1) { ?>
      <a href="<?php echo rtrim(home_url($wp->request), '/') . '?page=' . (string)($currentPage - 1) ?>" class="category__nav category__prev">
      <img src="<?php echo ROOT_CHILD_URI . '/assets/images/arrow-left.png'; ?>" class="category__img" />
      </a>
      <?php } ?>
      <?php if ($maxPage > $currentPage) {?>
      <a href="<?php echo rtrim(home_url($wp->request), '/') . '?page=' . (string)($currentPage + 1) ?>" class="category__nav category__next">
      <img src="<?php echo ROOT_CHILD_URI . '/assets/images/arrow-right.png'; ?>" class="category__img" />
      </a>
      <?php } ?>
   </div>
</div>
<?php } else { ?>
<div class="category__error">
   <h2 class="category__notfound">POST NOT FOUND</h2>
</div>
<?php
   }
   ?>

6. Code tạo menu

add_action( 'init', 'register_my_menus' );
function register_my_menus(){
    register_nav_menus( array(
    'main_menu' => __('Menu Chính', 'thaivietcan-blog')
    ) );
}

Đặt nó ở file function.php nhé cả nhà.

7. Hiễn thị menu menu ra ngoài giao diện

Hôm nay mình sẽ giới thiệu tới các bạn 2 cách để hiễn thị menu ra ngoài cực kì chất lượng.

Cách 1:

<?php wp_nav_menu(array(
    'theme_location' => 'main_menu',
    'menu_class' => '',
    'container' => false,
    'items_wrap' => '%3$s'
)); ?>

‘theme_location’ => ‘main_header’ Đây là điều kiện bắt buộc để hiễn thị menu. main_header mình đăng ký nó ở trên array.

Tiếp theo cách thứ 2:

<?php
$menuLocations = get_nav_menu_locations();
$menuID = $menuLocations['main-nav'];
$primaryNav = wp_get_nav_menu_items($menuID);
foreach ( $primaryNav as $navItem ) {
echo '<li class="menu-item menu-item-type-post_type menu-item-object-page"> <a href="'.$navItem->url.'" title="'.$navItem->title.'">'.$navItem->title.'</a> </li>';
}
?>

Cách này thì sau này chúng ta dể tùy biến để làm menu đa cấp hơn. Các bạn có thể quan tâm bài viết tạo menu đa cấp cho theme wordpress.

8. Code tạo sidebar

add_action( 'init', 'register_my_sidebar' );
function register_my_sidebar(){
    register_sidebar(
        array(
        'name' => esc_html__( 'Sidebar Main', 'thaivietcan-blog' ),
        'id' => 'sidebar-default',
        'description' => esc_html__( 'Add widgets here to appear in your footer.', 'thaivietcan-blog' ),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h2 class="widget-title">',
        'after_title' => '</h2>',
        )
    );
}

Các bạn nhớ đặt nó ở file function.php nha.

9. Hiễn thị sidebar ra ngoài giao diện

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar') ) : ?><?php endif; ?>

Code này thường đặt ở sidebar.php

10. Code lấy bài viết liên quan theo category

<?php
   $categories = get_the_category(get_the_ID());
   if ($categories){
       echo '<div class="relatedcat">';
       $category_ids = array();
       foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
       $args=array(
           'category__in' => $category_ids,
           'post__not_in' => array(get_the_ID()),
           'posts_per_page' => 5, // So bai viet dc hien thi
       );
       $my_query = new wp_query($args);
       if( $my_query->have_posts() ):
           echo '<h3>Các tin khác</h3><ul>';
           while ($my_query->have_posts()):$my_query->the_post();
               ?>
<li><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
   endwhile;
   echo '</ul>';
   endif; wp_reset_query();
   echo '</div>';
   }
   ?>

Code này thường đặt ở single.php sau nội dung bài viết nhé mọi người.

11. Code lấy nội dung rút gọn

Mình sẽ giới thiệu đến các bạn 2 cách.

Cách thư 1: Viết ở file function.php.

function my_excerpt_length($length){
return 80;
}
add_filter(‘excerpt_length’, ‘my_excerpt_length’);

Cách thứ 2:  Mình hay dùng nhất, đoạn code này mình viết trực tiếp vào nơi mà bạn mún hiễn thị

<p>
    <?php
        $theExcerpt = get_the_excerpt();
        if (strlen($theExcerpt) > 120) {
            echo substr($theExcerpt, 0, 120) . '(...)';
        } else {
            echo $theExcerpt;
        }
    ?>
</p>

Đoạn trên mình lấy 120 từ, nếu vượt hơn 120 từ thì sẽ cộng thêm phía sau dấu … nhé.

12. Code thêm custom logo ở khu vực tùy biến

add_theme_support(
	'custom-logo',
	array(
		'height'               => $logo_height,
		'width'                => $logo_width,
		'flex-width'           => true,
		'flex-height'          => true,
		'unlink-homepage-logo' => true,
	)
);

13. Code hiễn thị bài viết ngẫu nhiên

<div class="post_random">
   <?php
      $post_random = new WP_Query(array(
      'post_type' => 'post',
      'posts_per_page' => 6,
      'post_status' => 'publish',
      'orderby' => 'rand' // random bài viết ngẫu nhiên
      ));
      ?>
   <?php while($post_random->have_posts()) : $post_random->the_post(); ?>
   <li>
      <a href="<?php the_permalink();?>"><i class="fa fa-angle-right"></i><?php the_title();?></a>
   </li>
   <?php endwhile; wp_reset_postdata(); ?>
</div>

14. Code tính lượt xem cho bài viết

1. Đầu tiên hãy truy cập tệp Functions.php của theme hiện đang sử dụng của WordPress. Sau đó, sao chép mã bên dưới và dán nó trước thẻ đóng?> Của tệp Functions.php.

function gt_get_post_view() {
    $count = get_post_meta( get_the_ID(), 'post_views_count', true );
    return "$count views";
}
function gt_set_post_view() {
    $key = 'post_views_count';
    $post_id = get_the_ID();
    $count = (int) get_post_meta( $post_id, $key, true );
    $count++;
    update_post_meta( $post_id, $key, $count );
}
function gt_posts_column_views( $columns ) {
    $columns['post_views'] = 'Views';
    return $columns;
}
function gt_posts_custom_column_views( $column ) {
    if ( $column === 'post_views') {
        echo gt_get_post_view();
    }
}
add_filter( 'manage_posts_columns', 'gt_posts_column_views' );
add_action( 'manage_posts_custom_column', 'gt_posts_custom_column_views' );

2. Sau đó, sao chép đoạn mã dưới đây và dán vào tệp single.php trong vòng lặp while.

<?php gt_set_post_view(); ?>

3. Tiếp theo, sao chép mã sau và dán vào nơi bạn muốn hiển thị số lượt xem

<?= gt_get_post_view(); ?>

Như vậy bạn đã xong chức năng tính lượt xem cho bài viết. Nếu bạn muốn xem tính lượt xem dùng plugin thì tham khảo bài Cách đếm số lượt xem bài đăng trong WordPress

15. Cách chuyển JavaScript sang Footer trong WordPress

// Custom Scripting to Move JavaScript from the Head to the Footer
function remove_head_scripts() {
remove_action(‘wp_head’, ‘wp_print_scripts’);
remove_action(‘wp_head’, ‘wp_print_head_scripts’, 9);
remove_action(‘wp_head’, ‘wp_enqueue_scripts’, 1);

add_action(‘wp_footer’, ‘wp_print_scripts’, 5);
add_action(‘wp_footer’, ‘wp_enqueue_scripts’, 5);
add_action(‘wp_footer’, ‘wp_print_head_scripts’, 5);
}
add_action( ‘wp_enqueue_scripts’, ‘remove_head_scripts’ );

// END Custom Scripting to Move JavaScript

16. Cách xóa url category cha

// Remove Parent Category from Child Category URL
add_filter('term_link', 'tvc_category_parents', 1000, 3);
function tvc_category_parents($url, $term, $taxonomy) {
    if($taxonomy == 'category'){
        $term_nicename = $term->slug;
        $url = trailingslashit(get_option( 'home' )) . user_trailingslashit( $term_nicename, 'category' );
    }
    return $url;
}
// Rewrite url mới
function tvc_category_parents_rewrite_rules($flash = false) {
    $terms = get_terms( array(
        'taxonomy' => 'category',
        'post_type' => 'post',
        'hide_empty' => false,
    ));
    if($terms && !is_wp_error($terms)){
        foreach ($terms as $term){
            $term_slug = $term->slug;
            add_rewrite_rule($term_slug.'/?$', 'index.php?category_name='.$term_slug,'top');
            add_rewrite_rule($term_slug.'/page/([0-9]{1,})/?$', 'index.php?category_name='.$term_slug.'&paged=$matches[1]','top');
            add_rewrite_rule($term_slug.'/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$', 'index.php?category_name='.$term_slug.'&feed=$matches[1]','top');
        }
    }
    if ($flash == true)
        flush_rewrite_rules(false);
}
add_action('init', 'tvc_category_parents_rewrite_rules');
 
/*Sửa lỗi khi tạo mới category bị 404*/
function tvc_new_category_edit_success() {
    tvc_category_parents_rewrite_rules(true);
}
add_action('created_category','tvc_new_category_edit_success');
add_action('edited_category','tvc_new_category_edit_success');
add_action('delete_category','tvc_new_category_edit_success');

17. Không cho phóng to màn hình ở giao diện điện thoại

<meta name="viewport" content="width=device-width, initial-scale=1.0, 
minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

18. Code chống copy bài viết trên website

<script type="text/javascript">
$(document).ready(function(){
$('*').bind('cut copy paste contextmenu', function (e) {
    e.preventDefault();
})});
</script>

19. Hiễn thị category con theo category cha

<?php
   <?php
      $queried_object = get_queried_object();
      $parent = $queried_object->term_id;
      $categories = get_term_children( $parent, 'product_cat' ); 
      if ( $categories && ! is_wp_error( $category ) ) : 
      	echo '<ul>';
      	foreach($categories as $category) :
      	$term = get_term( $category, 'product_cat' );
      	global $wp_query;
      	$thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
      	$image = wp_get_attachment_url( $thumbnail_id );
      	echo '<img src="'.$image.'">';
      	echo '<li>';
      	echo '<a href="'.get_term_link($term).'" >';
      	echo $term->name;
      	echo '</a>';
      	echo '</li>';
      	endforeach;
      	echo '</ul>';
      
      endif;
      ?>

20. Code không cho update Core wordpress, plugin wordpress, theme wordpress

// Not Update Core WordPress
add_filter('pre_site_transient_update_core', '__return_null');

// Not Update Plugin
add_filter('pre_site_transient_update_plugins', '__return_null');

// Not Update Theme WordPress
add_filter( 'pre_site_transient_update_themes', '__return_null');

21. Code hiễn thị danh cha và danh mục con theo ID của danh mục cha

<?php
    $parent_cat_arg = array('hide_empty' => false, 'parent' => 0 );
    $parent_cat = get_terms('category',$parent_cat_arg);//category name

    foreach ($parent_cat as $catVal) {

        echo '<h2>'.$catVal->name.'</h2>'; //Parent Category

        $child_arg = array( 'hide_empty' => false, 'parent' => $catVal->term_id );
        $child_cat = get_terms( 'category', $child_arg );

        echo '<ul>';
            foreach( $child_cat as $child_term ) {
                echo '<li>'.$child_term->name . '</li>'; //Child Category
            }
        echo '</ul>';
    }
?>

22. Code  lấy tất cả tags

<ul class="tag_list">
     <?php 
        $tags = get_tags(array(
          'hide_empty' => false,
          'number' => 20
        ));
        foreach ($tags as $tag) {
            ?>
                <li><a href="<?php echo get_tag_link($tag->term_id); ?>"><?php echo $tag->name; ?></a></li>
            <?php
        }
    ?>
</ul>

23. Code lấy tags trong file single.php

<?php 
    $post_tags = get_the_tags();
     
    if ( $post_tags ) {
        foreach( $post_tags as $tag ) {
            ?>
            <li><a href="<?php echo get_tag_link($tag->term_id); ?>">
                <?php echo $tag->name; ?></a>
            </li>
            <?php
        }
    }
?>

Code này thông thường sẽ nằm ở single.php sau nội dung.

24. Lấy cấp bậc ( level ) của category

Copy đoạn code này bỏ vào file functions.php

// get level category
function get_the_level($id, $type = 'category') {
  return count( get_ancestors($id, $type) );
}

Tiếp theo copy đoạn này bỏ vào file category.php để lấy được giá trị nha.

global $wp_query;
$level = get_the_level( $wp_query->get_queried_object()->term_id, 'category' );
var_dump($level);

Code này phù hợp để các bạn làm nhiều giao diện cho trang category, nhiều cấp bậc khác nhau.

Tổng kết

Trên đây là những đoạn code thường gặp nhất trong lập trình theme wordpress. Hãy dùng và cho mình ý kiến nhé !

Cùng nhau học hỏi và đóng góp để cùng phát triển hơn nhé.