0

My objective is to alter the main query using pre_get_posts so I can search only through attachments and only ones that have specific tags assigned to them. These tags are displayed to the user using the_tags().

The logic is in place so my attachments have tags and this is confirmed using var_dump on this attachment page template: http://photonew.rasdesignmedia.com/surf-kayaking-mark-woolward-a633257/

The problem is that when I click on the tag link outputted by the_tags(), no posts are found (http://photonew.rasdesignmedia.com/tag/surfing/). My function to alter the main query currently outputs the query so I can see what is going on. The tag/terms are there yet the query can find no posts.

I have tested a non-pre_get_posts version of this using twentyseventeen theme with no customization and I still no posts are returned.

I have flushed things out via settings > permalinks.

I am finding several other posts of similar topic but most were either resolve with a permalink reset or were CPT.

I feel like I am missing something obvious.

function search_attachment_post_type($query) {

    if ( !is_admin() && $query->is_main_query() ) {

        if ($query->is_tag) {
            echo "This is a tag query. 404 Error is below the query dump.<br>";
            $query->set('post_type', 'attachment');
            $query->set('taxonomy', 'post_tag');
            echo '<pre>$query is set to post_type attachment and taxonomy to post_tag<br><br>'; var_dump($query); echo '</pre>';
        }
    }
}
add_action( 'pre_get_posts', 'search_attachment_post_type' );

1 Answer 1

0

That page isn't a 404, it's returning a status code 200. The title and body tags also indicate that the page is loading just fine.

A couple of things- there is no taxonomy argument. It would be redundant anyway, since the query already contains the queried taxonomy and term pulled from the parsed URL.

Your possible issue is outlined in this note from the WP_Query Codex page under type parameters:

'attachment' - an attachment. Whilst the default WP_Query post_status is 'publish', attachments have a default post_status of 'inherit'. This means no attachments will be returned unless you also explicitly set post_status to 'inherit' or 'any'.

1
  • post_status set to 'inherit' in my pre_get_posts function did the trick. Thank you! As for the 404, you are also correct,...that was just embarrassing.
    – Roger
    Aug 25, 2017 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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