Updating a field with a function in wordpress

493 Views Asked by At

I'm trying to code a function that will automatically tick a check box field in the back-end when the post status is set to 'publish'. This is in my functions.php btw.

function featured_post(){
if( get_post_status() == 'publish' )
{
update_post_meta( $post->ID, '_featured', '1' );
}
}

I've set the function to run in the post preview template by calling featured_post() but it doesn't seem to work. Can anyone point me in the right direction?

1

There are 1 best solutions below

1
On BEST ANSWER

You need to use action hooks in order to make your function work. In your case, you need to use the post_updated hook like the below:

function set_featured_post($post_ID, $post_after, $post_before){
  if( get_post_status($post_ID) == 'publish' ){
    update_post_meta( $post_ID, '_featured', '1' );
  }
}

add_action( 'post_updated', 'set_featured_post', 10, 3 );

Read more about this hook via WordPress Codex