I'm trying to use pre_get_posts to modify the query so that only schools that give student discounts are displayed on the archive page. The field in question is called 'student_discount' and is a checkbox, it returns 1 if true.

when i use get_post_custom to echo the value it is '_student_discount: Array'.

This is what I have currently:

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

UPDATE: SInce there's confusion over the underscore....the following code:

$custom = get_post_custom();
foreach($custom as $key => $value) {
 echo $key.': '.$value.'<br />';

Produces this output: _company_avatar: Array rating: Array _student_discount: Array _nhs_discount: Array

I don't think the get_post_custom() function prepends anything. The underscore comes form the meta box I think.

| improve this question | | | | |
  • The fact that _student_discount is an array indicates that you have multiple student_discount meta rows with value=1 matching the post ID. One cause of this could be calling add_post_meta() instead of update_post_meta() (which will update existing rows rather than inserting new ones) elsewhere in your code. – acobster Feb 13 '17 at 17:23
  • I'm just retrieving all the school and trying to filter out the ones that don't have student discount, in othere words I only want schools where 'student_discount' = 1. – Duck of Death Feb 13 '17 at 17:37
  • You refer to the field as both _student_discount and student_discount, are you sure you are querying the correct key? – Milo Feb 13 '17 at 17:43
  • Just thought I'd offer that suggestion since having more fields than you expect can cause problems down the road. Anyway, I believe "custom" fields (à la get_post_custom()) prepend a _ character to the key, but as Milo points out that's not what you're querying. – acobster Feb 13 '17 at 17:47
  • The reason some fields are prefixed with an underscore is so that those fields will be hidden from the generic Custom Fields meta box, that's how it filters those keys out for display. – Milo Feb 13 '17 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.