0
votes

I'm using Timber for Wordpress and when I use a custom query in archive.php to get posts of a custom post type, it returns posts of multiple post types.

I tried the exact same query in page.php and it worked perfectly.

Here's the query I'm using:

global $paged;
    if (!isset($paged) || !$paged){
        $paged = 1;
    }
$args = array(
    'post_type' => 'horse',
    'orderby' => 'title',
    'order' => 'ASC',
    'posts_per_page' => 20,
    'paged' => $paged
);
$context['horses'] = new Timber\PostQuery( $args );

I would expect that to return all items of post type 'horse', but other post types are also mixed in.

Any ideas why this might be happening?


I'm not sure if this is related, but I also added this to functions.php, inside the StarterSite class, in order to add my custom post type to the archive page:

function namespace_add_custom_types( $query ) {
    if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {

        // Get all your post types
        $post_types = get_post_types();

        $query->set( 'post_type', $post_types );
        return $query;
    }
 }

And this was added to the existing function named __construct:

add_filter( 'pre_get_posts', array($this, 'namespace_add_custom_types') );
1
From looking at the code, I can’t find anything that might be off. Can you make sure that it’s not another plugin that interferes with the query? You could try to deactivate all plugins and check if the error still happens.Gchtr
Sadly that didn't help. I was able to do what I want by creating a custom page template though, instead of relying on archive.php. The logic there is simpler so I must have added something to archive.php that was messing things up.Diego

1 Answers

1
votes

How are you calling it in the twig file?

{% for post in horses %}
{{ post.name }}
{% endfor %}

Also, are you sure the post type name is horse and not horses? If the wrong post type name is included in 'post_type' it would show all post types.