【问题标题】:Wordpress Custom Post Type Taxonomy - Get specific contentWordpress 自定义帖子类型分类 - 获取特定内容
【发布时间】:2017-06-02 04:44:05
【问题描述】:

我有一个包含食品的网站,并且我有一个名为食谱的自定义帖子类型。 我需要做的是从附加到产品的配方类别中显示 3 个帖子。 我已经创建了自定义帖子类型并将其附加到我的产品中,但我无法让它工作!我有点迷路了。我已经设法遍历食谱并获得 3 个帖子,但我不知道如何过滤掉食谱的类别。

例子:

-Recipe Categories
Sauce
Spicy

假设我有一个产品“Noodle”,我想展示 3 个来自 Sauce 类别的帖子。我无法显示它。我总是收到来自每个食谱类别的帖子。

这是我展示 3 个帖子的循环。

<?php $loop = new WP_Query( array( 'post_type' => 'recipes', 'posts_per_page' => 3 ) );
        while ( $loop->have_posts() ) : $loop->the_post(); ?>


            <a href="<?php the_permalink(); ?>">            

              <img src="<?php the_post_thumbnail_url(); ?>">
                <h4><?php the_title(); ?></h4>
                </a>

                <?php endwhile; ?>  

我尝试将分类类别添加到我的数组参数中,但没有任何反应! 这是我尝试做的(有很多变化):

$mytaxonomy = 'recipe_category';
$myterms = get_the_terms($post, $mytaxonomy);

然后我使用与上面相同的方法在数组中添加术语。 有人可以帮帮我吗?我迷路了,卡住了,但我需要知道为什么它不起作用,这样我才能提高自己。

【问题讨论】:

    标签: php wordpress loops post taxonomy


    【解决方案1】:

    WP_Query 也支持tax_query按类别获取帖子,试试吧:

    global $post;
    $terms = get_the_terms($post->ID, 'recipe_category');
    $recipe_cat_slug = array();
    foreach ($terms as $term)
    {
        $recipe_cat_slug[] = $term->slug;
    }
    $args = array(
        'post_type' => 'recipes',
        'posts_per_page' => 3,
        'tax_query' => array(
            array(
                'taxonomy' => 'recipe_category',
                'field' => 'slug', //can be set to ID
                'terms' => $recipe_cat_slug //if field is ID you can reference by cat/term number; you can also pass multiple cat as => array('sauce', 'spicy')
            )
        )
    );
    $loop = new WP_Query($args);
    

    希望这会有所帮助!

    【讨论】:

    • 这看起来不错,但我需要动态完成。我的意思是它需要检查产品的配方类别并将术语名称传递给您发布的循环!太感谢了!不知道 tax_query
    • 您在使用 WooCommerce 产品吗?还是来自自定义帖子类型?您的 productrecipes 是否共享相同的类别名称 slug?
    • 我正在使用 woocommerce 并且我已将分类 recipe_categories 附加到产品和食谱中
    • 我已经更新了我的答案,请查看。并且您想在产品详细信息页面中显示帖子吗?
    • 是的,我想在页脚之前的单个产品页面中显示我的帖子!
    猜你喜欢
    • 2016-10-28
    • 1970-01-01
    • 2013-06-22
    • 2014-10-23
    • 2011-06-26
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多