donglei2022 2019-07-04 13:11
浏览 56
已采纳

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

I made a template for my page in which I want to post the latest "topic" and to then post "articles" of the same category as this topic so I have to pass this category via a variable, I think.

I hope the code isn't to long

Thanks for any advice!

<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
 );

I seem to have made some kind of datatype error because when I try to include this template, I get the error: Object of class WP_Term could not be converted to string

  • 写回答

1条回答 默认 最新

  • douyu0852 2019-07-04 15:09
    关注

    The function

    get_the_category();
    

    returns an array of objects as more than one category can be associated with a post, I guess this could be causing the issue as in your $args2 it is expecting $mycat to be an ID.

    You can see what is returned by adding this to your template:

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

    If you knew it was always going to be only one term associated with a post you could acces the term_id using:

    $mycat[0]->term_id
    

    But it would probably be better to loop through be better to loop through $mycat

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型