【问题标题】:Can I show all categories and tag of each post in Wordpress?我可以在 Wordpress 中显示每个帖子的所有类别和标签吗?
【发布时间】:2021-10-06 07:24:21
【问题描述】:

我目前正在为 WordPress 中的帖子列表创建简码。这是我的代码

function mgc_post_default() { 


global $post;

extract(shortcode_atts(array(
    'cat'     => '',
    'num'     => '5',
    'order'   => 'DESC',
    'orderby' => 'post_date',
), $atts));

$args = array(
    'cat'            => $cat,
    'posts_per_page' => $num,
    'order'          => $order,
    'orderby'        => $orderby,
);

$output = '';

$posts = get_posts($args);

foreach($posts as $post) {
    
    setup_postdata($post);
    
    $output .= '<div class="movie-poster">' . get_the_post_thumbnail() . '</div>';
    $output .= '<div><h2><a href="'. get_the_permalink() .'">'. get_the_title() .'</a></h2></div>';
    $output .= '<div>' . get_the_date() . '</div>';
    $output .= '<div>' . get_the_content() . '</div>';
    $output .= '<div>' . get_field( "status" ) . '</div>';
    $output .= '<div>' . get_the_category( $id )[0]->name . '</div>';
    $output .= '<div>' . get_the_tags( $id ) [1]->name . '</div>';
}

wp_reset_postdata();

return '<div>'. $output .'</div>';
}

// Register shortcode

add_shortcode('mgc_post', 'mgc_post_default');

它正在工作,但是每个帖子的类别和标签刚刚出现 1。我想要的是它可以显示每个帖子的所有类别和标签信息。

所以我的问题是如何为每个帖子显示所有这些类别和标签?

谢谢,

【问题讨论】:

    标签: php wordpress function


    【解决方案1】:

    要检索帖子的所有类别,请使用 wp_get_post_categories 而不是 get_the_category。然后,您只需遍历 foreach 中的类别。

    条款相同。但是然后使用wp_get_post_terms

    所以是这样的:

    $posts = get_posts($args);
    
    foreach($posts as $post) {
        
        setup_postdata($post);
    
        $categories = wp_get_post_categories( $post );
    
        $foreach( $categories as $category ) { 
          
            $output .= '<div>' . $category->name . '</div>';
     
        } 
         
    }
    
    wp_reset_postdata();
    

    【讨论】:

      【解决方案2】:

      感谢@anotheraccount 的回答,但我已经解决了我自己的问题,方法是将此代码“get_the_tag_list()”和“get_the_category_list()”添加到$output

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-23
        • 1970-01-01
        • 2013-11-01
        • 1970-01-01
        相关资源
        最近更新 更多