Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP: Custom WordPress functions to fetch a list of registered post types that support a specific feature or a set of features. Inspired by Micah Wood's (@wpscholar) get-post-types-supporting.php (https://gist.github.com/wpscholar/6273186).
<?php
/**
* Get a list of post type names that support a specific feature.
*
* @since 4.4.0
*
* @global array $_wp_post_type_features Associative array of post types with accepted features.
*
* @param string|array $feature String of a single post type support feature or array
* (e.g., `'title'` or `array( 'title' => true )`).
*
* @return array $post_types Array of post type names that support a feature.
*/
function get_post_types_by_support( $feature ) {
global $_wp_post_type_features;
$features = ! is_array( $feature ) ? array( $feature => true ) : $feature;
$post_types = array_keys(
wp_filter_object_list( $_wp_post_type_features, $features )
);
return $post_types;
}
<?php
// Example usages
// Get post types
get_post_types_by_support( 'editor');
/* Outputs
Array
(
[0] => post
[1] => page
[2] => nav_menu_item
[3] => custom_post_type1
[4] => custom_post_type3
[5] => custom_post_type4
[6] => custom_post_type5
)
*/
/**
* Get a list of post types that support a specific feature.
*
* @author Travis Smith <t@wpsmith.net>
* @author Micah Wood <@wpscholar>
*
* @param string|array $feature String or array of post type supports (e.g., title, editor).
*
* @return array Array of post type names that support feature.
*/
function get_post_types_by_supports( $features, $operator = 'and' ) {
$features = ! is_array( $features ) ? (array) $features : $features;
$supports = array();
if ( 'and' === strtolower( $operator ) ) {
foreach ( $features as $feature ) {
$supports[ $feature ] = true;
}
return get_post_types_by_support( $supports );
} else {
$post_types = array();
foreach ( $features as $feature ) {
$post_types = array_merge( $post_types, get_post_types_by_support( $feature ) );
}
return array_unique( $post_types );
}
}
<?php
get_post_types_by_supports( array( 'genesis-entry-meta-before-content', 'genesis-layouts', ) );
/* Outputs
Array
(
[0] => post
[1] => custom_post_type1
[2] => custom_post_type2
[3] => custom_post_type3
)
*/
get_post_types_by_supports( array( 'genesis-entry-meta-before-content', 'genesis-layouts', ), 'or' );
/* Outputs
Array
(
[0] => post
[1] => attachment
[2] => custom_post_type1
[3] => custom_post_type2
[4] => custom_post_type3
[5] => custom_post_type4
[6] => custom_post_type5
[8] => page
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment