Home WordpressWordPress cơ bản Hiển thị bài viết liên quan trong wordpress

Hiển thị bài viết liên quan trong wordpress

by admincp

Ở bài trước bạn mình đã hướng dẫn làm thế nào để hiển thị bài viết phổ biến (popular posts) trong wordpress. Trong bài hôm nay mình sẽ hướng dẫn hiển thị bài viết liên quan khi xem bài viết chi tiết.

hiển thị bài viết liên quan trong wordpress (related post wordpress plugin)

Trước tiên bạn nên xem đoạn code trước khi cố gắng tìm plugin, để hiểu về nguyên lý đơn giản của nó.

Hiển thị bài viết liên quan trong wordpress không dùng plugin

< ?php
//related posts
//for use in the loop, list 5 post titles related to first tag on current post
 
  echo 'Related Posts';
  //get all post tags
  $tags = wp_get_post_tags($post->ID);
  $tag_ids = array();  
    foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;  
 
  $args=array(
    'tag__in' => array($tag_ids),
    'post__not_in' => array($post->ID),
    //'showposts'=>5,
	'posts_per_page'=>'5',
    //'caller_get_posts'=>1,	//for older wordpress
	'ignore_sticky_posts'   => 1
   );
  $my_query = new WP_Query($args);
  //try in category
  if(!$my_query->have_posts()) {
      //category
      $terms=wp_get_post_categories($post->ID,array('fields'=>'ids'));
	  unset($args['tag__in']);
      $args['category__in']=$terms;
      $my_query=new WP_Query($args);
  }
  if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
      <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to < ?php the_title_attribute(); ?>">< ?php the_title(); ?></a></p>
      < ?php
    endwhile;
	wp_reset_query();
  }
 ?>

– Bài viết liên quan của 1 bài viết được hiểu đơn giản là các bài viết có cùng category hoặc tags, chú ý bài viết liên quan thì loại trừ bài viết hiện tại. Đoạn code này đặt trong cặp while endwhile;

Hiển thị bài viết liên quan dựa vào category

Nếu bạn chỉ muốn lấy các bài viết liên quan dựa vào category, thì sử dụng hàm dưới đây, thêm đoan code này vào function.php của Genesis Child Theme.

/** Display related posts in Genesis based on Category  */
 
function related_posts_categories() {
if ( is_single ( ) ) {
global $post;
$count = 0;
$postIDs = array( $post->ID );
$related = '';
$cats = wp_get_post_categories( $post->ID );
$catIDs = array( );{
foreach ( $cats as $cat ) {
$catIDs[] = $cat;
}
$args = array(
'category__in'          => $catIDs,
'post__not_in'          => $postIDs,
'showposts'             => 5,
'ignore_sticky_posts'   => 1,
'orderby'               => 'rand',
'tax_query'             => array(
array(
'taxonomy'  => 'post_format',
'field'     => 'slug',
'terms'     => array(
'post-format-link',
'post-format-status',
'post-format-aside',
'post-format-quote' ),
'operator' => 'NOT IN'
)
)
);
$cat_query = new WP_Query( $args );
if ( $cat_query->have_posts() ) {
while ( $cat_query->have_posts() ) {
$cat_query->the_post();
$related .= '<li><a href="' . get_permalink() . '" rel="bookmark" title="Permanent Link to' . get_the_title() . '">' . get_the_title() . '</a></li>';
}
}
}
if ( $related ) {
printf( '<div><h3>Related Posts</h3><ul>%s</ul></div>', $related );
}
wp_reset_query();
}
}

Giải thích:

  • Hàm trên sẽ hiển thị randrom bài viết liên quan có chung category với bài viết hiện tại.
  • Chỉ định số lượng hiển thị bằng cách thay đổi giá trị 'showposts' => 5

Hiển thị bài viết liên quan dựa vào Tags

Trường hợp bạn muốn định nghĩa bài liên quan dựa là vào tags, thì sử dụng đoạn code sau đây. Thêm vào functions.php trong Genesis Child Theme.

/** Display related posts in Genesis based on Tags */
 
function related_posts_tags () {
if ( is_single ( ) ) {
global $post;
$count = 0;
$postIDs = array( $post->ID );
$related = '';
$tags = wp_get_post_tags( $post->ID );
foreach ( $tags as $tag ) {
$tagID[] = $tag->term_id;
}
$args = array(
'tag__in'               => $tagID,
'post__not_in'          => $postIDs,
'showposts'             => 5,
'ignore_sticky_posts'   => 1,
'tax_query'             => array(
array(
'taxonomy'  => 'post_format',
'field'     => 'slug',
'terms'     => array(
'post-format-link',
'post-format-status',
'post-format-aside',
'post-format-quote'
),
'operator'  => 'NOT IN'
)
)
);
$tag_query = new WP_Query( $args );
if ( $tag_query->have_posts() ) {
while ( $tag_query->have_posts() ) {
$tag_query->the_post();
$related .= '<li><a href="' . get_permalink() . '" rel="bookmark" title="Permanent Link to' . get_the_title() . '">' . get_the_title() . '</a></li>';
$postIDs[] = $post->ID;
$count++;
}
}
if ( $related ) {
printf( '<div><h3>Related Posts</h3><ul>%s</ul></div>', $related );
}
wp_reset_query();
}
}

Hàm này giống hàm trên chỉ có khác là bài viết liên quan dựa vào tag.

Trang trí CSS cho related posts

Có thể tham khảo đoạn CSS mẫu làm đẹp cho bài viết liên quan trong Genesis Thêm sau đây.

.related-posts {
margin: 10px 0;
}
.related-posts h3 {
font-size: 18px;
}
.related-posts ul {
list-style:none;
}
.related-posts ul li {
padding: 3px 0;
border-bottom: 1px dashed #ccc;
}
.related-posts ul li a{
font-size:14px;
text-decoration:none;
}

Hiển thị bài viết liên quan trong wordpress sử dụng plugin

Ngoài cách dùng code bạn có thể nhờ đến plugin để show bài viết liên quan khá hiệu quả và đáng tin cậy đó là:
yet-another-related-posts-plugin (tải ở file đính kèm phía dưới.)
Tải về xong, chúng ta kích hoạt plugin như bình thường.

yet-another-related-posts-plugin có widget cho bạn kéo vào sidebar hoặc cũng có thể chèn widget này vào mọi nơi trong template sử dụng hàm the_widget. Ví dụ sau đây mình thêm related post vào cuối nội dung bài viết trong single.php

<h2>< ?php _e('Sản phẩm liên quan','hoangwebtheme')?></h2>
<div class="products-grid clearer" id="upsell-product-table">
   < ?php the_widget('YARPP_Widget','title= &template=yarpp-template-hoangweb.php',array('before_title'=>'','after_title'=>'','before_widget'=>'','after_widget'=>''))?>
</div>

Nhìn thoáng qua, thấy plugin không có tính năng sử dụng file template ngoài để hiển thị dữ liệu related posts. Do vậy mạo muội đã can thiệp 1 chút xíu trong code của em nó để thỏa mãn tính tò mò của mình. Tuy nhiên mình đã cập nhật lại bài viết này, và plugin hiển nhiên có hỗ trợ. Bạn có thể muốn đọc tiếp cách này hoặc nhấn vào đây để xem cập nhật, Ở đây tôi đã tạo thêm thuộc tính template, widget này sẽ include file mà khai báo ở thuộc tính này. Sau đó bạn tạo file yarpp-template-hoangweb.php đặt ở root của theme và chép vào nội dung sau:

< ?php 
/*
YARPP Template: hoangweb simple
Author: mitcho (Michael Yoshitaka Erlewine)
Description: A simple example YARPP template.
*/
?>
< ?php
$new_row=1;$cols=3;$count=0;
?>
< ?php if (have_posts()):?>
< ?php while (have_posts()) : the_post();
$custom=get_post_custom();
$price=preg_replace('/[^d+]/','',isset($custom['price'])? $custom['price'][0]:'0');
 
if($new_row){ echo '<div class="row-fluid">';$new_row=0;}
 ?>
 <div class="product-wrapper span4" >
<div <?php post_class('product-block'); ?> id="post-< ?php the_ID(); ?>">
			<div class="product-content">
				<a class="product-image" href="<?php the_permalink(); ?>" title="< ?php echo esc_attr( sprintf( __( 'Permalink to %s', 'hoangwebtheme' ), the_title_attribute( 'echo=0' ) ) ); ?>">
				< ?php the_post_thumbnail('thumbnail',array('width'=>'208','height'=>'208'))?>
				</a>
		<div class="product-info">
			<h4 class="product-name"><a href="<?php the_permalink(); ?>" title="< ?php echo esc_attr( sprintf( __( 'Permalink to %s', 'hoangwebtheme' ), the_title_attribute( 'echo=0' ) ) ); ?>">< ?php the_title()?></a></h4>
				<div class="desc">< ?php the_excerpt()?></div>
																																				<div class="review"></div>
																																			<div class="contact">Liên hệ</div>
	<div class="actions">			                	
		<button type="button" title="Đặt mua" class="button btn-cart" onclick="setLocation('<?php the_permalink()?>')"><span><span>Đặt mua</span></span></button>
																																					</div>
																						</div>	
	< ?php edit_post_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '' ); ?>
									</div>
</div>
</div>
< ?php if(++$count==$cols){ echo '</div>';$count=0;$new_row=1;}?>
< ?php endwhile; 
if(!$new_row) echo '</div>';
?>			
< ?php else: ?>
< ?php _e('<p>Không có bài viết liên quan.

‘,’hoangwebtheme’)?>

Bạn cần cấu hình cho plugin một chút nữa nhé, truy cập settings-> YARRP. Plugin cung cấp khá nhiều tính năng cho bạn tùy biến lựa chọn như khóa chuyên mục và tag không cho phép hiển thị bài viết liên quan với thẻ đó, hay chỉ hiển thị những bài viết cũ cách đây vài ngày, tuần hoặc vài tháng đổ lại.

Plugin sẽ tự động gán bài viết liên quan vào cuối mỗi bài viết, bạn có thể bỏ tính năng tự động này bằng cách bỏ chọn Automatically display related content from YARPP Basic on. Áp dụng tương tự cho hiển thị trang và media liên quan.
bài viết liên quan yet-another-relate-post

Ngoài ra, bạn còn có thể trực tiếp tự chèn related post vào template, sử dụng hàm:

//related post
related_posts() ;
 
//related pages
related_pages();
 
//related media
related_entries();

Một số mục có thể điều chỉnh thêm như:

  • Maximum number of related posts: Điều chỉnh tối đa số lượng hiển thị của bài viết liên quan.
  • “Relatedness” options
    • Math threshold: số điều kiện thỏa mãn, nên đặt giá trị này là 1. Vì các bài viết liên quan chỉ cần chung 1 category/tag. Những ai không để ý, sẽ đánh giá sai về tính chính xác của plugin, nên website của họ không hiển thị related post theo ý muốn.
    • Titles: lọc bài liên quan dựa theo tiêu đề, tính năng này bạn phải nâng cấp.
    • Bodies: bạn phải nâng cấp mới sử dụng được.
    • Category/Chuyên mục: có vài lựa chọn sau.
      • consider: ràng buộc tiếp category cũng với title, bodies và tag.
      • do not consider: bỏ qua category.
      • consider with extra weight: bài viết liên quan có thể tìm trong category nếu trùng với post hiện tại. Không bắt buộc như “consider”.
    • Tag/Thẻ: giống như Category/Chuyên mục nhưng là tag.
    • Display results from all post types: hỗ trợ với tất cả post types.


Bài viết này mình mới cập nhật và đến hôm nay mới có dịp xem lại, quả đúng như người ta nói “đọc kỹ hướng dẫn trước khi dùng” :(. Bạn hoàn toàn có thể thay đổi giao diện hiển thị cho related post trên frontend bằng cách tạo các file template của plugin vào thư mục theme. Plugin có sẵn các template mẫu bạn có thể tham khảo trong thư mục plugins/yet-another-related-posts-plugin/yarpp-templates. Có 3 tùy chọn hiển thị:

  • List: danh sách đơn, ở đây bạn có thể chỉnh sửa thêm cấu trúc HTML đã định sẵn.
  • Thumbnails: nhấn vào Thumbnails, cũng thế.
  • Custom: cho phép sử dụng file template chứa trong folder plugin để tùy biến hiển thị theo ý bạn. Sử dụng template nào thì chỉ việc chọn nó là ok.

yet-another-relate-post-pick-template

Chọn related posts template trong widget.
yet another relate post widget

Nếu mục Custom chưa được bật lên, quay trở lại trang cấu hình plugin kéo xuống dưới bạn nhìn thấy mục “Display options for your website” đưa chuột vào ô Custom và nhấn vào Copy Templates để sử dụng các template mẫu tạo bởi plugin. Thao tác này sẽ copy các file template mẫu của plugin vào thư mục theme hiện tại của bạn. Về Sau này bạn có chỉnh lại cấu trúc HTML và tùy biến thêm code trong template bằng cách tạo mới dựa trên template cũ của plugin.
yet-another-relate-post-template

Chúng ta không sử dụng hack code ở trên nữa, thay vào đó sử dụng template trong widget với php như sau.

< ?php the_widget('YARPP_Widget','title=Related Posts&template=yarpp-template-hoangweb.php',array('before_title'=>'','after_title'=>'','before_widget'=>'','after_widget'=>''))?>

Cách sử dụng template của plugin trùng với tham số template mình sửa lúc trước. Trước khi sử dụng bạn cần xóa code của plugin và tải bản mới về.

YARPP có hỗ trợ custom post types?

Có. Để kích hoạt custom post types, bạn cần thiết lập thuộc tính yarpp_support=true vào thông tin cài đặt custom post type.

'yarpp_support' => true

Bạn có thể sửa lại mọi cài đặt post type trước đó tạo bởi plugin hoặc trong theme của bạn, xem cách sửa lại thuộc tính post type tại đây. Chẳng hạn như thế này, Chép đoạn code vào functions.php và sửa lại tên post type của bạn:

add_action( 'registered_post_type', 'hoangweb_label_rename', 10, 2 );
/**
 * Modify registered post type menu label
 * 
 * @param string $post_type Registered post type name. 
 * @param array $args Array of post type parameters.
 */
function hoangweb_label_rename( $post_type, $args ) {
    if ( 'mynews' === $post_type ) {
        global $wp_post_types;
        $args->yarpp_support =true;
        $wp_post_types[ $post_type ] = $args;
    }
} 

Hoặc khai báo taxonomy vào YARPP trong hàm đăng ký post type.

function property_listing() {

        $args = array(
            'description' => 'Property Post Type',
            'show_ui' => true,
            'menu_position' => 4,
            'exclude_from_search' => true,
            'labels' => array(
                'name'=> 'Property Listings',
                'singular_name' => 'Property Listings',
                'add_new' => 'Add New Property', 
                'add_new_item' => 'Add New Property',
                'edit' => 'Edit Properties',
                'edit_item' => 'Edit Property',
                'new-item' => 'New Property',
                'view' => 'View Property',
                'view_item' => 'View Property',
                'search_items' => 'Search Properties',
                'not_found' => 'No Properties Found',
                'not_found_in_trash' => 'No Properties Found in Trash',
                'parent' => 'Parent Property'
            ),
            'public' => true,
            'capability_type' => 'post',
            'hierarchical' => false,
            'rewrite' => true,
            'query_var' => true,
            'supports' => array('title', 'editor', 'thumbnail', 'author', 'comments'),
            'yarpp_support' => true
    );

       register_post_type( 'property' , $args );
       flush_rewrite_rules();
    }

Sau khi kích hoạt Custom Post Types cho YARPP, chúng ta truy cập trang cài đặt YARRP, tìm metabox “The Pool” và “Relatedness” nếu không thấy bạn mở tab “screen options” và kích hoạt nó lên.
Check vào mục “Display results from all post types” nếu bạn muốn hiển thị tất cả các post types hỗ trợ taxonomy rồi nhấn save change để xác định custom post type. Sau khi trang được load lại nếu wordpress của bạn có khai báo kiểu dữ liệu mới liên kết với taxnomy, bạn sẽ thấy có thêm taxonomy ở metabox “Relatedness” options. Ví dụ:
yarrp-custom-post-type
Chú ý: Bạn phải kích hoạt post types mới thấy các taxonomies của post type đó hiển thị trong mục “Relatedness” options.
Chọn tìm kiếm related posts tại taxonomy này, ví dụ trên, tôi chọn “consider”. Đừng quên nhấn Save Changes.

Nếu bạn muốn lập trình riêng cách sử lý hiển thị related posts, thì sử dụng filter yarpp_map_post_types. Cái này bạn tự tìm hiểu nhé.

Ngoài cách hiển thị nội dung related posts bằng cách gọi widget bởi hàm the_widget như ở trên, bạn nên sử dụng hàm tích hợp sẵn của YARRP. Với hàm yarpp_related chúng ta có thể tùy biến giao diện hiển thị theo ý bạn muốn. Xem cách dùng tham số ở dưới đây:

yarpp_related(array(
    // Pool options: these determine the "pool" of entities which are considered
    'post_type' => array('post', 'page', ...),
    'show_pass_post' => false, // show password-protected posts
    'past_only' => false, // show only posts which were published before the reference post
    'exclude' => array(), // a list of term_taxonomy_ids. entities with any of these terms will be excluded from consideration.
    'recent' => false, // to limit to entries published recently, set to something like '15 day', '20 week', or '12 month'.
    // Relatedness options: these determine how "relatedness" is computed
    // Weights are used to construct the "match score" between candidates and the reference post
    'weight' => array(
        'body' => 1,
        'title' => 2, // larger weights mean this criteria will be weighted more heavily
        'tax' => array(
            'post_tag' => 1,
            ... // put any taxonomies you want to consider here with their weights
        )
    ),
    // Specify taxonomies and a number here to require that a certain number be shared:
    'require_tax' => array(
        'post_tag' => 1 // for example, this requires all results to have at least one 'post_tag' in common.
    ),
    // The threshold which must be met by the "match score"
    'threshold' => 5,

    // Display options:
    'template' => , // either the name of a file in your active theme or the boolean false to use the builtin template
    'limit' => 5, // maximum number of results
    'order' => 'score DESC'
),
$reference_ID, // second argument: (optional) the post ID. If not included, it will use the current post.
true); // third argument: (optional) true to echo the HTML block; false to return it

Lưu ý nếu bạn sử dụng template có sẵn của plugin thay vì tự viết template mới thì để giá trị false, còn lại điền tên template chứa trong thư mục theme của bạn, bao gồm cả định dạng file .php
yarrp-default-template

Thay đổi hiển thị, với các tham số như: before_title, after_title, before_post, after_post, before_related, after_related, no_results, excerpt_length

Bạn có thể lấy related posts của một post chỉ định thông qua tham số $reference_ID, truyền ID của post bạn muốn lấy bài viết liên quan, và nhờ đó hàm này được hoạt động nằm ngoài loop.
Ví dụ: hiển thị related posts với taxonomy “Danh mục” ở trên.

echo yarpp_related( array('post_type' => array('mynews'),'require_tax' => array('news_tax' => 1)),get_the_ID());

Ở đây, bạn có thể chỉ định thêm post types, ngoài những post types taxonomy cấu hình mặc định trong yarrp settings, và các tham số khác.

Ngoài ra, có thêm hàm yarpp_get_related( $args, $reference_ID )yarpp_related_exist( $args, $reference_ID )..
– yarpp_get_related: trả về mảng danh sách đối tượng posts, giống như get_posts
– yarpp_related_exist: trả về giá trị true/false để cho biết related posts có dữ liệu không?
Các tham số sử dụng tương tự như yarpp_related.

Đấy là căn bản của plugin tạo bài viết liên quan mà mình thấy khá ổn. Một vài tính năng khác bạn tự tìm hiểu nha.

Chúc bạn thành công.

Để nhận được bài viết mới vui lòng đăng ký kênh kiến thức WordPress từ A-Z ở Form bên dưới. Bạn cũng có thể nhận được sự trợ giúp trên TwitterFacebook

Liên hệ

Công ty chuyên Thiết kế website uy tín nhất Miền Bắc: http://vinastar.net

Hotline tư vấn: 0989 48 3456

Nguồn: Sưu tầm trên internet

You may also like

Leave a Comment