Skip to content

Instantly share code, notes, and snippets.

@joshuadavidnelson
Last active December 11, 2021 10:54
Show Gist options
  • Save joshuadavidnelson/8321291 to your computer and use it in GitHub Desktop.
Save joshuadavidnelson/8321291 to your computer and use it in GitHub Desktop.
Check if a custom post type supports archives
<?php
/**
* Check if post type supports an archive
*
* @param string $post_type post type name
* @uses get_post_type
* @global object $post
* @returns boolean
* @author Joshua David Nelson
*/
if( !function_exists( 'cpt_has_archive' ) ) {
function cpt_has_archive( $post_type ) {
if( !is_string( $post_type ) || !isset( $post_type ) )
return false;
// find custom post types with archvies
$args = array(
'has_archive' => true,
'_builtin' => false,
);
$output = 'names';
$archived_custom_post_types = get_post_types( $args, $output );
// if there are no custom post types, then the current post can't be one
if( empty( $archived_custom_post_types ) )
return false;
// check if post type is a supports archives
if ( in_array( $post_type, $archived_custom_post_types ) ) {
return true;
} else {
return false;
}
// if all else fails, return false
return false;
}
}
@binzorellino
Copy link

What about:

if ( !function_exists( 'cpt_has_archive' ) ) {
	function cpt_has_archive( $post_type ) {
		$post_type_obj = get_post_type_object( $post_type )
		if ( !$post_type_obj->has_archive ) {
			return false;
		}
		return false;
	}
}

@joshuadavidnelson
Copy link
Author

Yes, that’s certainly simpler if you just want to check if a post type supports archives! Thanks for the comment.

For context, I believe the use case originally for this function required that it only return true for custom post types with archives (hence the _built_in argument).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment