将相关帖子添加到单个帖子wordpress模板

时间:2014-11-06 13:40:23

标签: php wordpress related-content

我试图在一个帖子页面中显示包含相关产品的模块。

我创建了一个名为" Product"的cpt,以及一个名为" category"的分类法。

我想要做的是在单个帖子页面中显示同一类别的其他产品。

到目前为止,我已成功添加功能wp_get_recent_post的其他帖子,但当然我会收到所有帖子。

如何将类传递给查询?

这是我的代码:

<?php
$args = array(
            'numberposts' => '4',
            'orderby' => 'rand',
            'post_type' => 'product',
            'post_status' => 'publish'
             );
            $recent_posts = wp_get_recent_posts( $args );
            foreach( $recent_posts as $recent ){
                echo '<div class="col-md-3"><a href="' . get_permalink($recent["ID"]) . '">'. get_the_post_thumbnail($recent["ID"], 'thumbnail' ) . $recent["post_title"].'</a> </div> ';
            }
?>

谢谢

编辑。

我解决了这个问题:

            $terms = get_the_terms( $post->ID , 'category' );
                if ( $terms != null ){
                foreach( $terms as $term );
                }

            $args = array(
            'post_type' => 'product',
            'post__not_in' => array($post->ID),
            'tax_query' => array(
                array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $term->slug))
                );

            $recent_posts = wp_get_recent_posts( $args );
            foreach( $recent_posts as $recent ){
                echo '<div class="col-md-3"><a href="' . get_permalink($recent["ID"]) . '">'. get_the_post_thumbnail($recent["ID"], 'thumbnail' ) . $recent["post_title"].'</a> </div> ';
                }

1 个答案:

答案 0 :(得分:1)

使用get_posts()codex):

$related = get_posts( $args );
foreach( $related as $post ){
    setup_postdata( $post );
    echo '<div class="col-md-3"><a href="' . get_permalink() . '">'. get_the_post_thumbnail( get_the_ID(), 'thumbnail' ) . get_the_title() . '</a></div>';
}
wp_reset_postdata();
相关问题