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
相关产品推荐
相关产品推荐

