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

如何修改代码在WordPress用户资料页展示指定自定义文章类型内容?

在WordPress用户资料页展示多类型文章并显示文章类型

要实现展示用户所有类型内容(包括page、product、自定义listing等)并显示文章类型的需求,修改代码的关键是在查询参数中指定要获取的文章类型,同时在循环中加入文章类型的显示逻辑,修改后的完整代码如下:

if ( is_user_logged_in() ):
    global $current_user;
    wp_get_current_user();
    
    // 指定要获取的文章类型,包含post、page、product和自定义的listing
    $author_query = array(
        'posts_per_page' => '-1',
        'author' => $current_user->ID,
        'post_type' => array('post', 'page', 'product', 'listing')
    );
    
    $author_posts = new WP_Query($author_query);
    
    while($author_posts->have_posts()) : $author_posts->the_post();
    ?>
        <div class="user-content-item">
            <!-- 显示文章类型的友好名称 -->
            <span class="post-type-label"><?php echo get_post_type_object(get_post_type())->labels->singular_name; ?></span>
            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
        </div>
    <?php           
    endwhile;
    
    // 重置查询,避免影响后续内容
    wp_reset_postdata();

else :
    echo "请先登录";
endif;

关键改动说明:

  • 指定多文章类型:在$author_query数组中添加post_type参数,值为包含所有需要展示的文章类型的数组,自定义文章类型直接填写注册时的slug(比如你的listing)
  • 显示文章类型:使用get_post_type_object(get_post_type())->labels->singular_name获取文章类型的友好名称(比如“产品”对应product,“页面”对应page),如果只需要显示原始slug,直接用get_post_type()即可
  • 重置查询:添加wp_reset_postdata(),避免查询影响页面后续的WordPress循环逻辑

如果后续需要新增其他自定义文章类型,只需要在post_type数组中添加对应的slug即可。

内容的提问来源于stack exchange,提问作者BENABDELOUED MED AMINE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:25:20