1

I'm testing the function wp_list_filter(), basically I want to know if post_type has some specific feature before making stuffs.

So I end up with this:

public static function get_post_types_with_support( $feature ) {
   global $_wp_post_type_features;
   $post_types = wp_list_filter( $_wp_post_type_features, array( $feature => 1 ) );

   return $post_types;
}

The problem is I do not understand why I can't get it working with custom post type while I gave some specific support to them.

For example, book post_type supports thumbnails, but I do not have it in my array when I display it. Where am I wrong?

EDIT : by feature I mean support. If my post_type supports this feature then I can use it. My function is supposed to return array with post_types that support my feature e.g thumbnail

2

As I noted on a comment and @toscho wrote in his answer, your code works if used after wp_loaded hook. The reason why it works for core post types if used on earlier hooks is WordPress register core post types 2 times: first time just after 'mu_plugins_loaded' hook and then again on 'init' hook (reference).

That said, if you want to use a solution that make no use of pseudo-private variables you can rely on the functions that WordPress has for the scope: get_post_types and post_type_supports, possibly using a sort of cache to improve performance on subsequents calls on same request, something like this:

function get_post_types_with_support( $feature ) {
  static $supports;
  if ( ! isset( $supports[$feature] ) ) {
    if ( ! did_action( 'wp_loaded' ) && current_filter() !== 'wp_loaded' ) {
      return new WP_Error( 'too-early', 'Are you in a hurry?' );
    }
    $supports[$feature] = array_filter( array_map( function( $type ) use( $feature )  {
      if ( post_type_supports( $type, $feature ) ) return $type;
    }, array_values( get_post_types() ) ) );
  }
  return $supports[$feature];
}
  • In fact I do not need that because I want to add my code on every post types. But I definitely keep this as reference if I have to make another choice. I should have checked the load, missed that. – JMau Mar 31 '14 at 16:45
1

Post types are registered on wp_loaded or init – after plugins and the theme are loaded.

Searching in $_wp_post_type_features list on plugins_loaded is too early. Be also aware that variable might change in the future. In WordPress, where almost everything is global, pseudo-private variables are marked with a leading underscore. Read that as a sign not to access these variables directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.