我正在构建一个目录网站,并且我不得不让foreach遍历多站点的博客ID。从代码中的注释可以看出,对博客ID的查询工作正常,print_r检查显示数组已填充,但当函数到达第一个foreach时,循环每次返回相同的结果,并且foreach循环中site_blog_id上的print_r显示为空。在循环中手动设置site_blog_id使得其余代码工作正常,因此它肯定与foreach处理数组有关。
我非常困惑,因为这看起来与我在开发人员网站上看到的很多代码 - foreach代码的例子相同,包括查询文档页面上的代码。我想知道我是否需要对持有数组的site_blog_ids变量做一些事情以使其与foreach一起工作,但坦率地说我被卡住了。 任何帮助将不胜感激! 大卫
/* get all subsite blog ids */
global $wpdb;
$site_blog_ids = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM wp_blogs where blog_id > 1"));
print_r( $site_blog_ids );
/* check output - shows "Array ( [0] => stdClass Object ( [blog_id] => 2 ) [1] => stdClass Object ( [blog_id] => 3 ) [2] => stdClass Object ( [blog_id] => 5 ) ) ". Looks fine? */
/* loop to iterate through the ids and display info from each blog */
foreach( $site_blog_ids AS $site_blog_id ) {
print_r( "siteid= ".$site_blog_id."</br>" );
/* check output - this shows $site_blog_id is empty, no value. That's not right, should be each blog ID in turn from the site_blog_ids array. */
$oldblog = $wpdb->set_blog_id( $site_blog_id );
/* sets the system to use the loop blog ID instead of the current one. Since site_blog_id is empty, this doesn't work so the rest of the code uses the current blog, not the intended one. */
global $post;
$first_posts = get_posts('p=1'); //get the first post
foreach ( $first_posts AS $post ) {
setup_postdata();
the_title();
the_excerpt();
the_content();
the_category();
}
}
/* Tell the $wpdb object to go back to using the current site */
$wpdb->set_blog_id( $oldblog );
答案 0 :(得分:1)
尝试以下方法:
/* loop to iterate through the ids and display info from each blog */
foreach( $site_blog_ids AS $site_blog_id ) {
print_r( "siteid= ". $site_blog_id->blog_id ."</br>");
/* check output - this shows $site_blog_id is empty, no value. That's not right, should be each blog ID in turn from the site_blog_ids array. */
答案 1 :(得分:0)
print_r( "siteid= ".$site_blog_id."</br>" );
是不正确的。
当它到达printr
部分时,它会将其视为字符串。
我认为你试图做的是:
echo "siteid=". print_r($site_blog_id, true) ."</br>";