如何修复“ WP_Term类的对象无法转换为字符串”

时间:2019-07-04 13:11:50

标签: php wordpress

我为自己的页面制作了一个模板,我想在其中发布最新的“主题”,然后发布与该主题相同类别的“文章”,因此,我认为必须通过变量传递该类别。 / p>

我希望代码不要太长

谢谢您的建议!

<div class="empty-topic">

<?php
$args1 = array(
  'post_type'   => 'topic',
  'post_status' => 'publish',
  'posts_per_page' => 1
 );

$theme = new WP_Query( $args1 );
  if( $theme->have_posts() ) :
?> <div class="topic-facts">
<?php
        $theme->the_post();

$mytemp = get_the_ID();
$mycat = get_the_category();
?>

            <h3 class="topic-title">"Thema: "<?php the_title(); ?></h3>             
            <p><?php echo get_post_field( 'facts' ); ?></p>
                         </div>
           <?php 
           wp_reset_postdata();
        ?>
<?php
else :
  esc_html_e( 'No articles have been found!', 'text-domain' );
endif;
?>

<?php
$args2 = array(
  'post_type'   => 'article',
    'cat' => $mycat,
  'post_status' => 'publish',
  'posts_per_page' => 3
 );

我似乎犯了某种数据类型错误,因为当我尝试包含此模板时,出现错误:WP_Term类的对象无法转换为字符串

1 个答案:

答案 0 :(得分:0)

功能

get_the_category();

返回一个对象数组,因为一个帖子可以关联多个类别,我想这可能是导致问题的原因,因为您的$ args2期望$ mycat是ID。

您可以通过将其添加到模板中来查看返回的结果:

echo '<pre>';
print_r($mycat);
echo '</pre>';

如果您知道与帖子相关的总是一个术语,则可以使用以下命令访问term_id:

$mycat[0]->term_id

但是遍历$ mycat可能会更好