You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义文章列表短代码如何展示单篇文章全部分类和标签

修改方案

你原有代码中直接通过固定下标取分类、标签数组的元素,所以只能输出单个结果,同时还存在使用未定义$id变量、函数未声明接收$atts参数的问题。你可以通过遍历分类、标签数组输出所有关联内容,修改后的完整代码如下:

function mgc_post_default($atts) { 
    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>';

        // 输出所有关联分类
        $categories = get_the_category();
        if (!empty($categories)) {
            $cat_names = [];
            foreach ($categories as $cat) {
                $cat_names[] = $cat->name;
            }
            $output .= '<div>' . implode('、', $cat_names) . '</div>';
        }

        // 输出所有关联标签
        $tags = get_the_tags();
        if (!empty($tags)) {
            $tag_names = [];
            foreach ($tags as $tag) {
                $tag_names[] = $tag->name;
            }
            $output .= '<div>' . implode('、', $tag_names) . '</div>';
        }
    }

    wp_reset_postdata();

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

// 注册短代码
add_shortcode('mgc_post', 'mgc_post_default');

核心修改说明

  • 补全了函数参数$atts的声明,避免PHP运行警告
  • 删除了未定义的$id变量,get_the_category()、get_the_tags()在文章循环内默认会自动读取当前文章ID
  • 先获取当前文章的全部分类/标签数组,遍历拼接所有名称后再输出,多个分类/标签之间默认用顿号分隔,你也可以根据前端样式需求替换为其他分隔符,或者调整为带跳转链接的分类/标签格式。

内容的提问来源于stack exchange,提问作者Lily Ferli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:48:01