【问题标题】:Wordpress get post from tagsWordpress 从标签中获取帖子
【发布时间】:2021-10-04 14:38:26
【问题描述】:

(首先我是 php 新手) 我有一个 wordpress 博客,在那里我写了一些关于 ppl 的文章,我将他们的名字添加为服装分类中的标签,以避免使用 polylang 的多语言字段。 我正在寻找一个允许为每个标签显示标签存在的帖子标题的循环。 示例 => 帖子名称:“厨师能做什么?” (标记为 Alex P.) 结果:-Alex P. “厨师能做什么?” 2020 年 5 月 10 日 - “世界番茄” 2020 年 12 月 15 日。 我必须为每个人(标签)制作一个手风琴。

我已经开始编写代码,但我不是在寻找解决方案,我迷路了。

<?php $tag_args = array(
'orderby' => 'title',
'order' => 'ASC'    
);
?>
<ul id="Genre-List">
<li>DEFAULT</li>
<?php
$terms = get_terms(
array(
    'taxonomy'   => 'chef',
    'hide_empty' => false,
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
    print_r($terms);
foreach ( $terms as $term ) { 
        
?>
    <li><a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
        <?php echo $term->name; ?>
    </a></li>
<?php
}
}
?>

感谢有人能帮忙解决这个问题。我真的很生气。

【问题讨论】:

    标签: php wordpress post tags taxonomy


    【解决方案1】:

    如果您要获取与任何自定义分类术语相关联的所有帖子,则需要使用 tax_query 查询帖子,而不是简单地检索所有术语。

    // get 'chef' taxonomy
    $terms = get_terms([
        'taxonomy' => 'chef',
        'hide_empty' => false,
    ]);
    
    // get any posts with one of the 'chef' taxonomy terms associated with it
    $query = new WP_Query([
        'post_type' => 'post',
        'tax_query' => [[
            'taxonomy' => 'chef',
            'field' => 'term_id',
            'terms' => array_column($terms, 'term_id'),
            'operator' => 'IN',
        ]],
    ]);
    
    // loop and output posts
    while ($query->have_posts()) {
        $query->the_post();
    
        var_dump(get_the_title());
    }
    

    【讨论】:

    • 这段代码是有效的,但我认为不完全是我需要的。就我而言,对于每位厨师,我都需要与他们相关的文章,而不是完整的帖子列表。我们已经有了厨师名单。 Gordon Ramsey - 鸡肉日期 - 豆类 Morimoto - 寿司 - 鱼 这个代码在一个字符串中给了我这个答案:字符串(35)“Chicken Chicken Chicken,你在哪里?” string(51) "寿司沙拉"
    • @Daniele 你的意思是文章是不同的帖子类型(例如,页面而不是帖子?)如果是这样,请尝试将post_type 更改为page
    猜你喜欢
    • 2015-12-27
    • 2010-12-04
    • 2012-08-29
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 2011-08-29
    • 2018-06-24
    • 2021-08-23
    相关资源
    最近更新 更多