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

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

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀