Wordpress - 帖子2帖子:参数错误无效

时间:2014-10-15 00:32:50

标签: php wordpress foreach

我正在使用帖子2帖子来连接我的自定义帖子类型。到目前为止,一切似乎都很好,除了在档案中列出我的连接。我有两个连接分配给一个自定义帖子类型。这就是为什么我使用此处所述的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()错误。

但如果我单独使用其中任何一个就没有错误。如果你帮助我,我会很高兴的。

1 个答案:

答案 0 :(得分:2)

您实际上正在覆盖变量$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();
}