Bài viết liên quan wordpress

bai viet lien quan wordpress , bài viết liên quan wordpress ,
Sau đây mình cũng trình bày 2 thủ thuật bài viết liên quan mình sưu tầm được của hdit và blog thạch phạm

Shortcode bài viết liên quan

/* Shortcode bai viet lien quan */
function dtrung_rp_shortcode($atts){
  extract(shortcode_atts(array(
/* Số bài viết hiển thị */
    'count' => '5',
    'title' => 'Bài viết liên quan',
    ), $atts));
  global $post;
/* lấy theo category */
  $current_category = get_the_category($post->ID);
  $current_category = $current_category[0]->cat_ID;
  $this_category = '';
  $tag_ids = array();
  $tags = get_the_tags($post->ID);
  if ($tags) {
    foreach($tags as $tag) {
      $tag_ids[] = $tag->term_id;
      }
 } else {
    $this_category = $current_category;
        }
  $args = array(
    'post_type' => get_post_type(),
    'numberposts' => $count,
    'orderby' => 'date',
    'order' => 'DESC',
    'tag__in' => $tag_ids,
    'cat' => $this_cat,
    'exclude' => $post->ID
    );
  $dtrung_rp = get_posts($args);
    if ( empty($dtrung_rp) ) {
      $args['tag__in'] = '';
      $args['cat'] = $current_category;
      $dtrung_rp = get_posts($args);
      }
    if ( empty($dtrung_rp) ) {
      return;
     }
  $post_list = '';
  foreach($dtrung_rp as $re_post) {
    $post_list .= '<li><a href="' . get_permalink($re_post->ID) . '">' . $re_post->post_title . '</a></li>';
    }
    return sprintf('
      <div class="dtrung-related-posts">
        <h3>%s</h3>
        <ul>%s</ul>
      </div>
    ', $title, $post_list );
    }
add_shortcode('dtrung_related_posts', 'dtrung_rp_shortcode');

cách dùng [dtrung_related_posts] nhét vào chỗ cần hiển thị 
Tiếp theo 
// Hàm xác định thẻ </p> đầu tiên
function count_paragraph( $insertion, $paragraph_id, $content ) {
   $closing_p = '</p>';
   $paragraphs = explode( $closing_p, $content );
   foreach ($paragraphs as $index => $paragraph) {
      if ( trim( $paragraph ) ) {
         $paragraphs[$index] .= $closing_p;
      }
      if ( $paragraph_id == $index + 1 ) {
         $paragraphs[$index] .= $insertion;
      }
   }
   return implode( '', $paragraphs );
// Chèn shortcode bài viết liên quan vào sau thẻ </p> đầu tiên
add_filter( 'the_content', 'insert_shortcode_related_posts' ); 
function insert_shortcode_related_posts( $content ) {
   $related_posts= do_shortcode('[dtrung_related_posts]');
   if ( is_single() ) {
      return count_paragraph( $related_posts, 1, $content );
   }
   return $content;
}
Sau đó
<?php echo do_shortcode('[dtrung_related_posts]') ?>
Và tôi thấy cách trên hơi dài nhưng các bạn đấy là  tôi sưu tầm được thôi còn lại chúng ta làm theo cách sau này tôi thấy ngắn hơn
WordPress Related Posts
bạn có thể làm rất nhanh tôi thấy rất hay hãy dùng blugin nếu chúng ta ngại viết code
SHARE

trungthan

  • Image
  • Image
  • Image
  • Image
  • Image

0 nhận xét:

Đăng nhận xét