WordPress CPT areas查询导致后续自定义字段调用失效问题及解决方案
WordPress自定义文章类型查询与自定义字段调用冲突解决
问题场景
开发过程中已创建名为Areas的自定义文章类型(CPT),需要将该CPT下的所有内容输出到下拉选择框,初始实现代码如下:
<form action="<? bloginfo('url'); ?>" method="get"> <select name="page_id" id="page_id"> <?php global $post; $args = array( 'numberposts' => -1, 'show_option_none' => __( 'None' ), 'orderby' => 'title', 'hide_empty' => false, 'post_type'=>'areas', 'hierarchical' => true, 'suppress_filters' => true); $posts = get_posts($args); foreach( $posts as $post ) : setup_postdata($post); ?> <option value="<? echo $post->ID; ?>"><?php the_title(); ?></option> <?php endforeach; ?> </select> <input type="submit" name="submit" value="view" /> </form>
故障表现
上述代码可正常生成下拉选择框,但会导致页面后续的自定义字段调用失效,例如下方调用文章mainimg自定义字段的代码,删除上述查询代码即可正常输出,保留查询代码则无法返回正确值:
<img src="<?php if(get_post_meta($post->ID, 'mainimg', true)) { echo get_post_meta($post->ID, 'mainimg', true); } ?>">
解决方法
冲突根源为自定义查询过程中直接覆盖了全局$post变量,且调用setup_postdata修改了WordPress主查询的上下文,导致后续依赖全局$post的逻辑读取的是自定义查询的最后一条文章数据,而非当前页面对应数据。
修复方案如下:
- 将循环遍历的变量名从
$post修改为$post2,避免覆盖全局变量 - 直接通过自定义变量输出文章属性,无需调用依赖全局上下文的
the_title()模板标签,替换为echo $post2->post_title
修复后的查询代码如下:
<form action="<? bloginfo('url'); ?>" method="get"> <select name="page_id" id="page_id"> <?php $args = array( 'numberposts' => -1, 'show_option_none' => __( 'None' ), 'orderby' => 'title', 'hide_empty' => false, 'post_type'=>'areas', 'hierarchical' => true, 'suppress_filters' => true); $areas_posts = get_posts($args); foreach( $areas_posts as $post2 ) : ?> <option value="<? echo $post2->ID; ?>"><?php echo $post2->post_title; ?></option> <?php endforeach; ?> </select> <input type="submit" name="submit" value="view" /> </form>
补充:也可选择在自定义查询结束后调用wp_reset_postdata()恢复全局$post变量,同样可以解决冲突。
内容的提问来源于stack exchange,提问作者Dean O
相关产品推荐
相关产品推荐

