Question

hello

I want to display post based on his ID. This post could be a default 'post', 'page' or other registered custom post type. In query I sould specify all CPT names which I want to use, for eg.

 'post_type' => array('post', 'page', 'my_cpt')

My question is how can I set 'post_types' automatically for all registered post types, without manually specify them?

I'm striving for something like that:

$post_types = ALL-POST-TYPES-NAMES;
$the_query = new WP_Query(
  array(
    'post_type' => $post_types,
    'p' => ID,
  )
);

Thanks!

Était-ce utile?

La solution

You can get a list of post types with the get_post_types() function:

$post_types = get_post_types();

In your case you'll want to set the second $output parameter to names (since that's what you need to pass to the post_type argument), and you'll probably want to set the $args in the first argument so that only public post types are returned, otherwise you could end up with weird stuff like menu items and revisions:

$post_types = get_post_types( [ 'public' => true ], 'names' );

However, it looks like you're just looking for a specific post based on the ID. If that's the case, then you don't need post types or a query at all. Just pass the ID to get_post():

$post = get_post( $id );
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top