I want to execute a function, myfunction() [hypothetically named], whenever a page is updated in the admin. The function doesn’t do anything to the content that is saved—it just runs an unrelated task elsewhere.
I read that the post_updated
hook is good to use for this, but I cannot seem to get this code to run:
add_action('post_updated', 'myfunction');
function myfunction() {
// check if this is a page
$id = get_the_id();
if ( is_page($id) ) {
// do stuff here
}
}
I’m sure I’m missing something obvious; do I have to pass in/return parameters ($post_ID, $post_after, $post_before,
from what I gather in the WordPress Hooks Database) for it to work? If I just want the ID, do I still have to pass in/return the other two?
2 Answers
You should be able to get the ID of the post through the $_POST
variable.
EDIT: Maybe you should try doing this on the save_post
action, like so, but save_post
sometimes runs on other instances (ie. Autosave Drafts), so you’ll want to do some more verifying. save_post
will also return the ID as one of the function arguments so you already have that handy.
add_action('save_post', 'myfunction');
function myfunction( $id ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// check if this is a page
if ( 'page' == $_POST['post_type'] ) {
// Return nothing if the user can't edit this page
if ( !current_user_can( 'edit_page', $id ) )
return;
// do stuff here, we have verified this is a page and you can edit it
}
}
Just tested this on localhost, works good for me.
Used a bit of code from here and you should read up on the save_post
action if you decide to try this out!