Lists Posts from CPT that match the Title of the Page

I am trying to get all the posts associated with the Title of a page.

This is what I currently have:

    <?php
        $title_to_tag_posts_query = new WP_Query( array(
        'tag' => get_queried_object()->post_name 
        ) );

        while ( $title_to_tag_posts_query->have_posts() ) : $title_to_tag_posts_query->the_post(); ?>
        <p>
            <a href="https://wordpress.stackexchange.com/questions/215904/<?php the_permalink() ?>" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
        <?php the_date(); ?>
        </p>

    <?php endwhile; ?>

It works in pulling all the posts where the tag matches the title of the Page. Except, it doesn’t work with posts under a custom post type, even though they are tagged. So I almost have it, but not quite. I’m still missing content from the CPT posts.

I’ve been playing around with it by using some conditionals but all I seem to do is break it. The CPT I am trying to get the posts from has the capability_type of ‘post’ so I’m pretty sure that’s not the problem. I think I just may be missing the proper conditional or appropriate way to query for this?

1 Answer
1

By default wp_query returns posts of type ‘post’ only, unless tax_query is set. So you would have to set 'post_type' => array( 'post', 'your-cpt-name' ) to get posts from your CPT as well.

You can set the post_type to any as well, but that will also return other post types, such as attachments that might have the same tag.

Leave a Comment