donglei2022
donglei2022
2019-07-04 13:11

如何修复“类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 douyu0852 2年前

    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

    点赞 评论 复制链接分享