WordPress.org

Ready to get started?Download WordPress

Forums

WordPress Custom Post Type Query (2 posts)

  1. Manan
    Member
    Posted 6 months ago #

    I have this query for custom filed values (array based values):

    <?php
        // args
        $args = array(
            'numberposts' => -1,
            'post_type' => 'villa',
            'meta_query' => array(
            'relation' => 'AND',
                array(
                        'key' => 'amenities',
                        'value' => 'Internet',
                        'compare' => 'LIKE'
                    )
                )
            );
        // get results
        $the_query = new WP_Query( $args );
    
        // The Loop
    ?>
    <?php if( $the_query->have_posts() ): ?>
        <ul>
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <li>
                <?php echo the_title(); ?>
            </li>
        <?php endwhile; ?>
        </ul>
    <?php endif; ?>

    Now I want to generate bellow part dynamically:

    array(
                'key' => 'amenities',
                'value' => 'Internet',
                'compare' => 'LIKE'
            )
        )

    Bellow is my implemented code but now working:

    $amenities_exp = explode(",", $villa_amenities);
        $aCount = 0;
    
        $args = 'array(
              \'numberposts\' => -1,
              \'post_type\' => \'villa\',
              \'meta_query\' => array(
              \'relation\' => \'OR\',';
    
        for($a=0; $a<count($amenities_exp); $a++){
            "array(
                    'key' => 'amenities',
                    'value' => '".$amenities_exp[$a]."',
                    'compare' => 'LIKE'
                )";
            if($aCount != count($amenities_exp) - 1){
                echo ",";
            }else{
                echo "";
            }
            $aCount++;
        }
    
        "));";
  2. bcworkz
    Member
    Posted 6 months ago #

    You're trying to build a complex string that looks like an array definition, but you need an actual array, not a string that looks like one. You can build up a meta_query array in a loop, then pass the final result as part of the whole WP_Query arguments array. Something like this, with the specifics taken out to better demonstrate the concept:

    $meta_args = array('relation' => 'AND');
    foreach $amenities_exp as $amenity {
       $meta_args[] = array( 'value' => $amenity,);
    }
    $args = array('meta_query' => $meta_args);

    Flesh out the array definitions of this structure and it should work for you.

Reply

You must log in to post.

About this Topic