0

I'm looking for a solution similar to here, except I want to keep attachment pages for attachments in a specific category.

I tried adding the below function, but it's still redirecting all of them:

add_action( 'template_redirect', 'test_attachment_redirect', 10 );
function test_attachment_redirect() {
    if( is_attachment() && !is_category('keep')) {
        $url = wp_get_attachment_url( get_queried_object_id() );
        wp_redirect( $url, 301 );
    }
    return;
}

For context, my attachments do have categories with this function:

function add_categories_to_attachments() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'add_categories_to_attachments' );
2
  • attachments don't have categories, it is the posts they're attached to that have the category, for this reason testing the attachment ID for the presence of a category, or using functions that operate on the main loop such as is_category will never work for this. Also keeping in mind that an attachment can appear in a post in that category, but not be attached, since attachments can be used in multiple places, but can only have 1 parent post. What's the problem that doing this solves for you? Perhaps there are alternatives that can be suggested you are unaware of
    – Tom J Nowell
    Commented May 6, 2023 at 18:41
  • Thanks, I edited my question to give a little more context
    – BlueHelmet
    Commented May 6, 2023 at 19:22

1 Answer 1

0

The problem is that is_category does not do what you thought it does. is_category( 'keep' ) tests that the current page is a category archive for the category keep, it does not check if the current attachment/post is in the keep category.

The official WordPress developers docs for is_category start with:

Determines whether the query is for an existing category archive page.

https://developer.wordpress.org/reference/functions/is_category/

Instead, what you want is to check if the current post has a category assigned, aka has_category:

has_category( string|int|array $category = '', int|WP_Post $post = null ): bool

Checks if the current post has any of given category.

https://developer.wordpress.org/reference/functions/has_category/

1
  • has_category worked, thanks!
    – BlueHelmet
    Commented May 7, 2023 at 16:12

Your Answer

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

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