vishnu vishnu - 1 month ago 7
PHP Question

Manipulating a PHP variable inside WP_Query in WordPress

* This question may be quite long so hope to bear with me *

Was trying to group address under a particular city dynamically.

Layout sample:

enter image description here

So based on the sample layout above, Cupertino belongs to CA and so is displayed below it.

The city is selected inside an ACF group.

I tried to query the cities by the following code:

<?php
$counter = 0;
$cityArray = array();
?>

<?php $loop = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'branches_locations', 'orderby'=>'post_id', 'order'=>'ASC' ) ); ?>

<?php while( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
$city = get_field('city');
if(!in_array($city, $cityArray))
{
$cityArray[$counter] = get_field('city');
$counter++;
}
?>

<?php endwhile; ?>
<?php wp_reset_postdata(); ?>

<?php
foreach ($cityArray as $i)
{
$loopCity = $i;

?>

<?php echo "city before loop is $i"; ?>
<?php $loop = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'branches_locations', 'meta_key' => 'city', 'meta_value'=> '$i', 'order' => 'ASC' ) ); ?>

<?php echo "city after loop is $i"; ?>


The value of the
$i
variable do display as the sample below shows:

enter image description here

However, the WP_Query seems to not recognize the variable
$i
.

If I used the following:

<?php $loop = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'branches_locations', 'meta_key' => 'city', 'meta_value'=> 'Los Angeles', 'order' => 'ASC' ) ); ?>


instead of:

<?php $loop = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'branches_locations', 'meta_key' => 'city', 'meta_value'=> '$i', 'order' => 'ASC' ) ); ?>


The query outputs all address under Los Angeles.

What could I be doing wrong?

Answer

Seems that you're passing on a variable as string.

Try:

$loop = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'branches_locations', 'meta_key' => 'city', 'meta_value'=> $i, 'order' => 'ASC' ) );
Comments