2

I want to fire a function when a new post (cpt) is published.

function my_publish( $new_status, $old_status, $post ) {
    if ( $new_status == 'publish' && 'publish' !== $old_status ) {
          // do s.th.
    }
    debug_to_console( $post );
}
add_action( 'transition_post_status', 'my_publish', 10, 3 );

So when I hit the "Add New" button, the function is fired and I get my console log with the $post content. And that's it.

The function than never fires again. Neither when I publish the post nor when a post is updated or the status of a post is changed.

I also tried the common other hooks like:

add_action('future_to_publish', 'my_publish');
add_action('new_to_publish', 'my_publish');
add_action('draft_to_publish' ,'my_publish');
add_action('auto-draft_to_publish' ,'my_publish');

those never did anything.

I did a lot of research the last days and tried a lot of different solutions but nothing helped to get me over this... any Ideas?

5
  • My recommendation would be to test with the core post or page post types, in order to narrow down the source of your problem. If your custom post type does not use wp_insert_post() to create or modify posts the hooks will not be fired.
    – NateWr
    Jul 1 '16 at 9:57
  • @NateWr I tried also on normal posts and pages. Just forgott to mention it in the question. my_publish only fires, when the "Add New" button is clicked, doesn't matter which post-type.
    – fab5
    Jul 1 '16 at 11:59
  • Something sounds off about your setup, because by default clicking "Add New" on the post page does not create a post. The auto-draft isn't created until you've typed something into the title or post editor.
    – NateWr
    Jul 1 '16 at 15:58
  • @NateWr I just checked on a completely new and plain WP-installation. And the same result as above. The function gets fired as soon as I het the "add new" button. And when I update a post, it doesn't do anything...
    – fab5
    Jul 5 '16 at 15:31
  • OK, I got the bug! The function debug_to_console( $post ); caused the problem. This was echoing a <script> tag....
    – fab5
    Jul 5 '16 at 17:18
-1

This will do something when you publish a post in the backend.

function my_publish( $post_id ) {
   if ( ( $_POST['post_status'] === 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) {
     error_log('WordPress would be better if it did not use Google Fonts.  Looking forward to the system fonts.');
   }
}
add_action( 'publish_yourCustomPostType', 'my_publish', 10, 3 );

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.