0

I am trying to get an array of all the post types except for attachments and pages. I've been able to do this with one exclusion like this:

get_post_types(
    array(
        'name' => 'page',
        'public' => false
    ),
    'names',
    'not')
);

This returns all post types except for page as expected. However, I can't seem to get it to work if I try to exclude multiple names. I figured I could just pass in an array like this:

get_post_types(
    array(
        'name' => array('page','attachment'),
        'public' => false
    ),
    'names',
    'not')
);

But this doesn't exclude either of the post types I am trying to exclude. Any ideas?

2
  • what are you doing with the result of the function? It may be trivial to do this by just skipping or removing the post types you don't want from the array and making no changes to get_post_type args at all. You don't have to do it all via the arguments
    – Tom J Nowell
    Jul 19 at 20:00
  • @TomJNowell I am using it for my post_type query arg to query all posts regardless of post type. I would prefer to generate it dynamically so as not to have to modify it whenever a new post type is added. Jul 19 at 20:03

1 Answer 1

1

The query args you're passing to get_post_types() are handled by the underlying function wp_filter_object_list(), which isn't designed to handle advanced querying operations like "if key value (not) in array".

Since you're just getting the names of post types, use the native PHP function array_diff to filter the out the ones you don't want:

$post_types = array_diff( get_post_types(), [ 'page', 'attachment' ] );

FWIW, if you were getting post type objects, you could use array_filter with something like:

$post_type_objects = array_filter( get_post_types( [], 'objects' ), function ( $post_type_object ) {
    return ! in_array( $post_type_object->name, [ 'page', 'attachment' ] );
});
1
  • Excellent, thank you so much! Jul 19 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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