How to get posts with specific taxonomies in Controller

I am working on a portfolio website where the main post type is a custom post type, ‘jetpack-portfolio’.

All post are organized under the custom taxonomy ‘jetpack-portfolio-tag’; I’d like to have a module (a partial??) that renders on single.blade.php that shows posts with the same taxonomy.

However, I cannot seem to get this working. If I am picking up the MVC pattern correct, the function in Controllers/App.php should be mainly responsible for retrieving the posts from the “Model,” where it is passed into Views and called primarily through {{ }} syntax as $variables… right? So I think my function sameTags() should return an array through which I will @foreach loop in the view…

Anyway, here is the code snippet in App.php

// This function returns posts in the same taxonomy
// returns array
public function sameTags() {
    $terms = get_the_terms(get_post(), 'jetpack-portfolio-tag');
    $termsstrings = array_map(
        function ($item) {
            return [$item['slug']];
               }, $terms);
    $posts = get_posts([
        'post_type' => 'jetpack-portfolio',
        'posts_per_page'=> '6',
        'tax_query' =>
                'taxonomy' => 'jetpack-portfolio-tag',
                'field'    => 'slug',
                'terms'    => $terms
    return array_map(function ($post) {
        return [
            'portfolio-tags' => get_the_terms($post->ID, 'jetpack-portfolio-tag'),
            'permalink' => get_the_permalink($post->ID),
            'title' => get_the_title($post->ID),
            'excerpt' => get_the_excerpt($post->ID),
            'content' => apply_filters('the_content', $post->post_content),
            'thumbnail' => get_the_post_thumbnail($post->ID, 'large'),
    }, $posts);

This is giving me this lovely error:

( ! ) Fatal error: Uncaught Error: Cannot use object of type WP_Term as array in /srv/www/riledigital.test/current/web/app/themes/riledigital-one/app/Controllers/App.php on line 70

Does anyone have any thoughts on this? Thanks.

Hey @riledigital - the error message is telling you exactly what the problem is:

( ! ) Fatal error: Uncaught Error: Cannot use object of type WP_Term as array in /srv/www/riledigital.test/current/web/app/themes/riledigital-one/app/Controllers/App.php on line 70

On line 70 of App.php, you are trying to use a term object as if it were an array.

So you should be asking yourself:

  1. Where on line 70 am I using a term object?
  2. What about how I’m using it is how I would use an array?
  3. How are term objects different from arrays?

This is probably line 70:

return [$item['slug']];

but if not, take a look at whatever line 70 actually is. I’m sure you can track it down from here. :slight_smile:

This topic was automatically closed after 42 days. New replies are no longer allowed.