Wordpress pre_get_posts不会更改查询

时间:2017-02-13 14:35:49

标签: php wordpress

我正在尝试使用pre_get_posts来修改查询,以便只有提供学生折扣的学校才会显示在存档页面上。有问题的字段称为“student_discount”,是一个复选框,如果为真,则返回1.

当我使用get_post_custom回显值时,它是'_student_discount:Array'。

这就是我目前的情况:

function show_discounts( $query ) {
   if( !is_admin() && $query->is_main_query()  && is_post_type_archive( 'job_listing' ) ) {
    $query->set( 'meta_query', array(        
        array(
              'key' => 'student_discount',
              'value' => 1,
              'compare' => '='
        ),
  ));       
}
add_action( 'pre_get_posts', 'show_discounts' );

1 个答案:

答案 0 :(得分:0)

试试吧。

改变这个:

is_post_type_archive( 'job_listing' )

为此:

$query->query_vars['post_type'] === 'job_listing' )

结果:

function show_discounts( $query ) {
   if( !is_admin() && $query->is_main_query() && $query->query_vars['post_type'] === 'job_listing' ) {
    $query->set( 'meta_query', array(        
        array(
              'key' => 'student_discount',
              'value' => 1,
              'compare' => '='
        ),
  ));       
}
add_action( 'pre_get_posts', 'show_discounts' );

如果你能够让它发挥作用,请告诉我。