Ben Potter
Ben Potter

Reputation: 875

wordpress add_action('save_post', 'my_function) not working

I am trying to trigger an even upon saving / updating a post in wordpress... see here:

add_action('save_post', 'generate_location');

function generate_location($post_id) {   
    echo "hey"; 
}

the problem is that its not working... any ideas why? Syntax?

Upvotes: 1

Views: 3509

Answers (2)

James Kemp
James Kemp

Reputation: 349

I don't know whether you got this working, but I was having the same issue and discovered how to fix it!

in wp-includes/post.php on line 2940 (at the time of writing), this if/else is run whilst saving a post:

if ( !empty($page_template) && 'page' == $data['post_type'] ) {

You will notice that, if there is an error with the template the function stops there and save_post is never called.

In my case, the posts I was trying to save were imported from a pre-existing site. The new site had no page templates at all, so WP was still trying to save the page with the template from before, failing, and thus; save_post was never called.

I added

/* Template Name: Default Template */

to page.php, bulk edit, selected the template and saved. Remove the template name from page.php (as it shows up twice(, and now save_post is triggered every time.

This was the solution in my case anyway. i'm sure it'll affect someone else, somewhere down the line.

Upvotes: 1

Ian Dunn
Ian Dunn

Reputation: 3680

WordPress implements the Post/Redirect/Get pattern to avoid duplicate form submissions, so you're not going to see anything echo'd from a save_post callback.

Instead, you can do a wp_die( 'hey' ) instead, or log something to the database or file system.

Upvotes: 4

Related Questions