Support

Account

Home Forums General Issues Get all posts that have at least one value in a group

Solving

Get all posts that have at least one value in a group

  • Hello,

    I should check if within my query created with args there is at least one value present within the many fields within a group. Is it possible?

    This is the code to be developed:

    $args = array(
      'cat'             => 3,
      'post_type'			  => 'post',
      'posts_per_page'  => $atts['partite'],
      'meta_query' 		  => array(
        'relation'      => 'AND',
        array(
            'key'			  => 'data_match',
            'compare'		=> '>=',
            'value'			=> date_i18n('Y-m-d H:i'),
            'type'			=> 'DATETIME'
        ),
        array(
          ...
          <what here?>
          ...
        ),
      ),
      'order'     => 'ASC',
      'orderby'  => 'meta_value',
      'meta_key' => 'data_match',
    );

    This is the current structure of my group:
    Group
    -Group
    –Value
    –Value
    -Group
    –Group
    —Value
    —Ecc…

    Thanks!

  • Well, yes it would be possible, but it’s probably going to cause performance issues with the query, it might event time out your site. You need to check every value.

    group sub field meta keys are as follows

    
    "{$group_field_name}_{$sub_field_name}"
    

    nested group fields

    
    "{$group_field_name}_{$nested_group_field_name}_{$sub_field_name}"
    
    
    $args = array(
      'cat'             => 3,
      'post_type'			  => 'post',
      'posts_per_page'  => $atts['partite'],
      'meta_query' 		  => array(
        'relation'      => 'AND',
        array(
            'key'			  => 'data_match',
            'compare'		=> '>=',
            'value'			=> date_i18n('Y-m-d H:i'),
            'type'			=> 'DATETIME'
        ),
        array(
          'relation' => 'OR',
          array(
            'key' => 'meta_key',
            'value' => ''
            'compare' => '!='
          ),
          // repeat the above array for every field you want to check
        ),
      ),
      'order'     => 'ASC',
      'orderby'  => 'meta_value',
      'meta_key' => 'data_match',
    );
    
  • $my_query = new WP_Query($args));
    if($my_query->have_posts()) {
       while($my_query->have_posts()) {
          $my_query->the_post();
          /* Add all the fields your checking for here - I'm sure there is a prettier way to do this */
          if( !empty(field_1) || !empty(field_2) || !empty(field_3) || !empty(field_4) ) {
             true;
             /* Do whatever you want now */
          } else {
             /* Do Nothing? This has an empty field */
             false;
          }
       }
    }

    You can check for it when the loop it output; this way you’re not looping through every time to check each specific field, you only loop through once and don’t show it on output.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.