将相关文章添加到帖子

时间:2016-05-05 作者:Zayd Bhyat

我一直在努力让相关文章继续下去。我尝试了几种方法,但这是唯一一种给我结果的方法,但随机发布的帖子会显示出来,而不是文章中与之相关的帖子。

<?php           
    $args=array(\'tag_in\'=>$tags,
    \'exclude\'=>$post->ID,
    \'post_per_page\'=> 4,
    \'ignore_sticky_posts\'=>1,
    \'post_type\'=>array(\'ms\',\'gnd\',\'events\',\'news_article\',\'opinions\',\'projects\',\'tenders\',\'videos\',\'products\'));
    $rel_pst=get_posts($args);
    $count = 0;
    if($tags){
        foreach($rel_pst as $rel):setup_postdata($rel);//Loop through and find related posts
            if($count==4)
            {
                break;
            }
        $image = wp_get_attachment_image(get_post_thumbnail_id($rel->ID),\'related-posts\');
        //$tagy=$tags[$count];
        //Counts iterations to place aricles on seperate sides 


        if (($count  == 0)||($count == 2)){// first article start
            echo \'<div class="posts_wrapper">\';
            echo \'<article class="item_left">\';
        }
        if(($count == 1)||($count == 3)){// second article start
            echo\'<article class="item_right">\';
        }
?>  
<div class="pic"> <a href="<?php echo get_permalink($rel); ?>" class="w_hover img-link img-wrap"> <?php echo $image; ?></a> </div>
<h3><a href="<?php echo get_permalink($rel);?>"><?php echo get_the_title($rel); ?></a></h3>
<div class="post-info"> <a href="<?php echo get_permalink($rel);?>" class="post_date"></a> <a href="<?php echo get_permalink($rel); ?>" class="comments_count"></a> </div>
</article>
<?php 
    if(($count == 1)||($count == 3)){//second article/4th end
        echo \'</div>\';
    }   
        $count ++;
        endforeach;
    }           
//wp_reset_postdata(); ?>
任何帮助都将不胜感激

2 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

1) 它是tag__in (两条下划线)2)get_the_tags() 返回对象数组,您需要ID:

if ( $the_tags = get_the_tags() ) {
    // https://developer.wordpress.org/reference/functions/wp_list_pluck/
    $the_tags = wp_list_pluck( $the_tags, \'term_id\' );
}

$rel_pst = get_posts( array(
    \'tag__in\'             => $the_tags,
    \'exclude\'             => $post->ID,
    \'post_per_page\'       => 4,
    \'ignore_sticky_posts\' => true,
    \'post_type\'           => array(
        \'ms\',
        \'gnd\',
        \'events\',
        \'news_article\',
        \'opinions\',
        \'projects\',
        \'tenders\',
        \'videos\',
        \'products\',
    ),
));

if ( $rel_pst ) {
    // Do your thing
}

SO网友:cybmeta

不知道$tags 变量(您没有向我们显示),我在代码中看到的唯一错误是tag_in Argument,正确的是tag__in (注意双精度_).

另外,请注意tag__in 使用核心标记分类法。默认情况下,自定义帖子类型不支持此分类法,只有标准帖子类型支持此分类法。