You need to enable JavaScript to run this app. WordPress查询custom post type时如何动态调用custom field值作为post_type参数
优惠活动
大模型
产品
解决方案
定价
更多

WordPress查询custom post type时如何动态调用custom field值作为post_type参数

解决方法

你之前的写法是直接把字段的meta key字符串传给了post_type,系统只会把它当成普通的文章类型名称,不会自动读取对应字段值,所以会失效。你需要先获取当前页面的issue-no自定义字段值,再把它传入查询参数里即可实现动态匹配。

另外更推荐使用WP_Query替代query_posts,query_posts会修改WordPress主查询,容易引发分页、其他查询异常等问题。

推荐代码示例

<?php
// 先获取当前页面的issue-no自定义字段值,Toolset创建的字段默认前缀为wpcf-
$current_issue = get_post_meta( get_the_ID(), 'wpcf-issue-no', true );

// 安全校验:字段值存在、且对应自定义文章类型真实存在时再执行查询
if ( ! empty( $current_issue ) && post_type_exists( $current_issue ) ) {
    // 初始化自定义查询
    $issue_query = new WP_Query( array(
        'post_type'      => $current_issue,
        'posts_per_page' => -1, // 调取该类型下所有文章
        'post_status'    => 'publish', // 只查询已发布的内容
    ) );

    if ( $issue_query->have_posts() ) :
        while ( $issue_query->have_posts() ) : $issue_query->the_post();
?>
            <h2><?php the_title(); ?></h2>
            <!-- 其他文章字段输出代码可补充在此处 -->
<?php
        endwhile;
        // 重置post数据,避免影响页面其他查询
        wp_reset_postdata();
    endif;
}
?>

如果一定要沿用query_posts的写法(不推荐),可以改成以下写法:

<?php
$current_issue = get_post_meta( get_the_ID(), 'wpcf-issue-no', true );
if ( ! empty( $current_issue ) && post_type_exists( $current_issue ) ) {
    query_posts( array(
        'post_type' => $current_issue,
    ) );
    while ( have_posts() ) : the_post();
?>
        <h2><?php the_title(); ?></h2>
<?php
    endwhile;
    // 重置主查询
    wp_reset_query();
}
?>

内容的提问来源于stack exchange,提问作者R-G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 05:24:07