【问题标题】:Manipulating a PHP variable inside WP_Query in WordPress在 WordPress 中操作 WP_Query 中的 PHP 变量
【发布时间】:2016-10-27 09:54:53
【问题描述】:

*这个问题可能比较长,希望大家多多包涵*

试图在特定城市下动态分组地址。

布局示例:

所以根据上面的示例布局,Cupertino 属于 CA,因此显示在其下方。

在 ACF 组中选择了城市。

我尝试通过以下代码查询城市:

                    <?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"; ?>

$i 变量的值确实如以下示例所示:

但是,WP_Query 似乎无法识别变量 $i

如果我使用以下内容:

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

代替:

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

查询输出Los Angeles下的所有地址。

我做错了什么?

【问题讨论】:

    标签: php wordpress advanced-custom-fields


    【解决方案1】:

    似乎您将变量作为字符串传递。

    试试:

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

    【讨论】:

    • 非常感谢!它解决了我的问题。忘记了很多,因为我是很长时间的前端开发人员。
    猜你喜欢
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2016-12-31
    • 2013-09-26
    • 2014-09-05
    • 1970-01-01
    相关资源
    最近更新 更多