WordPress.org

Ready to get started?Download WordPress

Forums

get_post_types returns more than expected (4 posts)

  1. helgatheviking
    Member
    Posted 3 years ago #

    according to the codex get_post_types accepts a taxonomies parameter, but it isn't explained exactly how this works. i thought that it would return the post type this taxonomy is registered to, but that doesn't seem to be the case.

    $post_args = array(
    	'public'   => true,
    	'taxonomies' => array('genre'),
    	'show_ui' => true
    ); 
    
    $post_types = get_post_types($post_args);

    when i print out the $post_types variable, i get both posts and my custom post type to which the genre taxonomy is registered. So I am wondering if it is possible to have get_post_types only the post type associated with the taxonomy argument.. or at least explain how this parameter is supposed to work.

  2. Ov3rfly
    Member
    Posted 2 years ago #

    Ran into the same problem, caused a sleepless night, have opened a ticket, I consider this as a bug.

    http://core.trac.wordpress.org/ticket/19148

  3. helgatheviking
    Member
    Posted 2 years ago #

    cool. i probably should have done that myself 8 months ago and it might have been fixed by now!

    hate sleepless code nights...

  4. Ov3rfly
    Member
    Posted 2 years ago #

    The codex has been changed, 'taxonomies' is not listed there any more.

    Here a workaround which filters get_post_types($args, 'names'); results by taxonomies.

    $args = array(
    	'public'   => true,
    	'show_ui' => true
    );
    $post_types = get_post_types($args, 'names');
    
    $taxonomies = array('genre');
    $post_types = array_filter( $post_types, function ( $post_type ) use ($taxonomies) {
    	return (0 == count( array_diff( $taxonomies, get_object_taxonomies( $post_type ) ) ) );
    } );

    After the filter the $post_types array only contains post types which have at least the taxonomy genre.

    Note: If you specify multiple taxonomies in this workaround, e.g. $taxonomies = array('genre', 'image', 'video');, the post type needs to have all of them, otherwise it is filtered.

Topic Closed

This topic has been closed to new replies.

About this Topic