Wordpress-Posts 2 Posts:无效的参数错误


Wordpress - Posts 2 Posts: Invalid argument error

我使用posts 2 post来连接我的自定义post类型。到目前为止,一切似乎都很好,只是在档案中列出了我的连接。我有两个连接分配给一个自定义帖子类型。这就是我使用each_connected方法的原因https://github.com/scribu/wp-posts-to-posts/wiki/each_connected此处描述。

<?php
$my_query = new WP_Query( array(
    'post_type' => 'movie'
));
p2p_type( 'movies_to_actors' )->each_connected( $my_query, array(), 'actors' );
p2p_type( 'movies_to_locations' )->each_connected( $my_query, array(), 'locations' );
while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<?php the_title(); ?>
<?php
echo '<p>Actors:</p>';
foreach ( $post->actors as $post ) : setup_postdata( $post );
    the_title();
endforeach;
wp_reset_postdata();
echo '<p>Filming locations:</p>';
foreach ( $post->locations as $post ) : setup_postdata( $post );
    the_title();
endforeach;
wp_reset_postdata();
?>

当我尝试从2个连接获取数据时,它会给出warning: Invalid argument supplied for foreach()出错。

但如果我单独使用它们中的任何一个,都不会出错。如果你能帮我做这件事,我会很高兴的。

您实际上正在覆盖变量$post

$post更改为其他内容,比如$p

echo '<p>Actors:</p>';
foreach ( $post->actors as $p ) : setup_postdata( $p );
    the_title();
endforeach;
wp_reset_postdata();
echo '<p>Filming locations:</p>';
foreach ( $post->locations as $p ) : setup_postdata( $p );
    the_title();

更新:

对于问题warning: Invalid argument supplied for foreach()

我认为$post->locations设置不正确,或者不是一个数组,只是添加了一个条件

if ( isset($post->locations) && is_array($post->locations) ) {
    echo '<p>Filming locations:</p>';
    foreach ( $post->locations as $post ) : setup_postdata( $post );
        the_title();
}