I'm pretty new to php so forgive me if this is an easy one.

I've been trying all day to add actions in a loop and I just can't get it to work. I'm trying to modify a wp plugin so that it will trigger for all custom post types in the install as follows:

$args = array(
      'public'   => true,
      '_builtin' => false
foreach ( get_post_types( $args ) as $type ){
add_action( "publish_" . $type, 'duplicate_title_buwp_bc' ) ;

I can add the actions individually, but of course that means I need to knw what post types are loaded in advance.

Any help would be greatly appreciated.

  • 1
    What action is this hooked to run on? You can’t do this until all post types have been registered. – Milo Jan 4 '18 at 21:54
  • Where is this code running? In a plugin? Is it running on particular hook? – Tom J Nowell Jan 4 '18 at 22:10
  • I'm forking Duplicate Title Validate in order to get it to support custom post types, I'm placing this code immediately after the plugin adds the action for standard post types. The plugins that load the custom poost types are already loaded so that should be ok I hope. But I do admit I am an absolute novice at this. – Venutius Jan 4 '18 at 22:26
  • Thanks for the advice guys! I was getting pretty frustrated there, convinced my code was wrong, but not thinking it could be in the wrong place – Venutius Jan 4 '18 at 22:34

As Milo hints at in their comment, custom post types can only be registered on the init hook. Therefore, if you are trying to get all the public but not builtin post types before init, then get_post_types() will return an empty array. (You can use get_post_types() to get the builtin post types before init.)

What you need to do is hook in after init and then get the post types. I'd use wp_loaded since at this point, WordPress is fully loaded.

add_action( 'wp_loaded', 'wpse290170_wp_loaded' );
function wpse290170_wp_loaded() {
  $types = get_post_types( [
      'public'   => true,
      '_builtin' => false
  ] );
  foreach ( $types as $type ){
    add_action( "publish_" . $type, 'duplicate_title_buwp_bc' ) ;
  • Ah now I get it, after init, I placed your code after the init and it worked a dream, as easy as that! Thanks very much for your help. Wordpress is a big animal to get your headround for a beginner but hopefully I'll get there. This was supposed to be my easy starter project. Thanks again. – Venutius Jan 4 '18 at 22:32

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.