1

The following code gets the "organisation" taxonomy terms associated with the last 20 "article" or "viewpoint" posts.

First, it gets the posts, $recent_posts. Second, it pushes each of those "organisation" terms on to a new array, $recent_companies.

Later, I deduplicate them and display those terms. It all works fine.

The only thing is, with debugging enabled, I can see that the line foreach ($orgs_in_post as $org_single) { throws the following PHP warning:

Warning: Invalid argument supplied for foreach()

It doesn't stop the code working. I've only just discovered the warning.But I'd like to eliminate it. So what is going on with this code?

          <?php
          // Get latest posts
          $args = array(
            'numberposts' => 20,
            'offset' => 0,
            'category' => 0,
            'orderby' => 'post_date',
            'order' => 'DESC',
            'include' => '',
            'exclude' => '',
            'meta_key' => '',
            'meta_value' =>'',
            'post_type' => array('article','viewpoint'),
            'post_status' => 'publish',
            'suppress_filters' => true
          );
          $recent_posts = wp_get_recent_posts( $args, ARRAY_A );

                $recent_companies = array();
          // Get companies in latest posts
          foreach ($recent_posts as $post) {
            // get terms
            $orgs_in_post = get_the_terms($post['ID'], 'company');
            foreach ($orgs_in_post as $org_single) {
              array_push($recent_companies, $org_single->term_id);
            }
          }
1

According to the documentation, get_the_terms() returns an array of WP_Term objects, or a boolean false value, or a WP_Error object. The last two won't work with foreach().

You could update your code to check for these conditions:

$orgs_in_post = get_the_terms($post['ID'], 'company');
if ( is_array( $orgs_in_post ) ) {
    foreach ($orgs_in_post as $org_single) {
        array_push($recent_companies, $org_single->term_id);
    }
}
  • 1
    Oh, so I'm basically advised to CHECK whether get_the_terms() resulted in a populated array (as opposed to false or WP_Error. If so, cycle through them as I already was... ? – Robert Andrews Nov 27 '19 at 21:59
  • This seems to work. – Robert Andrews Nov 27 '19 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.