Cloud Confusing

Explaining hosting, AWS, Wordpress, static sites, and all manner of cloud solutions.

If you are writing a typical WordPress wp query you might not even mention the “post_type” filter, where you limit the post types returned in your query.

If you are looking for a specific post type, or possibly a custom post type, then you will use

'post_type' => 'yourCustomPostTypeName'

in order to only get results from that custom post type (CPT).

But what if you want you want to run a query to get the names of the post types, not the posts themselves?

It turns out that a query like this is simple to run, but not very intuitive.

You’ll want to start your wp_query with:

$args = array(
'post_type' => get_post_types(),
'post_status' => 'publish',

this will ensure that your query looks for any post type with published posts.

Alternatively a more recommended method is:


$args = array(
'public'   => true,
'_builtin' => false
);
$output = 'names'; // 'names' or 'objects' (default: 'names')
$operator = 'and'; // 'and' or 'or' (default: 'and')
$post_types = get_post_types( $args, $output, $operator );

which was recommended in the post types documentation.

Either way, the important thing to do is to rely on the get_post_types call but then to filter that based on your need. The main thing most people will want to do here is to filter out non-public post types. That’s what the publish and _builtin filters do in this case.

Another way to go about this would be:


$post_types = get_post_types( array ( 'public' => true, '_builtin' => FALSE ), 'objects' );
foreach ( $post_types as $post_type => $properties ) {
{
printf(
'<a href="/%1$s">%2$s</a><br>',$post_type, $properties->labels->name);
}} ?>

This will get the custom post types without any of the built-in ones, like your Advanced Custom Field post type, which you in all likelihood don’t want to appear in your list. This is useful for building a list of post types, which are often used like categories in sites like this FCC ID Lookup where each category of content has different requirements and thus different templates (handled by post types).

Hope this helps!

December 31st, 2021

Posted In: Web Development

Tags:


© Cloudconfusing.com 2022 | Privacy Policy | About | UTM Creator | CVE Reporting