我有两个foreach循环,我正在使用WordPress生成的对象.
在我看来,这些应该都是一样的.但是,他们没有.注意$post并$not_a_post在循环中:
A:
$array_A = array( 'posts_per_page' => 2 );
$get_posts_A = get_posts( $array_A );
foreach ( $get_posts_A as $post ) { //uses $post
the_title();
}
Run Code Online (Sandbox Code Playgroud)
B:
$array_B = array( 'posts_per_page' => 5 );
$get_posts_B = get_posts( $array_B );
foreach ( $get_posts_B as $not_a_post ) { //uses $not_a_post
the_title();
}
Run Code Online (Sandbox Code Playgroud)
该唯一的区别是,我使用的是可变$post的条件第一个循环.
我一直认为(显然,错误地)第二个条件变量只是一个占位符.所以我可以做$ x,$ y等.
有人可以向我解释为什么这个foreach循环需要变量$post吗?
那是因为the_title()依赖于一个名为完全$post来自外部范围的变量,顺便说一下这是一个糟糕的设计理念 - 它应该作为参数传递给函数,例如:
the_title($some_id || $some_resource);
Run Code Online (Sandbox Code Playgroud)
编辑:实际WP允许您传递帖子ID,在这里检查代码.
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |