0

I need to make the default author for all new posts be already selected but leave existing posts unmodified.

So since the default post status is "draft" i thought to only do this if the post is a draft like so:

add_filter( 'wp_insert_post_data' , 'update_author', '99', 2 );

function update_author($data , $postarr) {
if ($postarr['post_status'] == 'draft') {
    $data['post_author'] = 45;
 }
  return $data;
}

But then it never runs, so i tried the other way around. Do it when it isn't "published" but then it runs for all new and existing posts...

add_filter( 'wp_insert_post_data' , 'update_author', '99', 2 );

function update_author($data , $postarr) {      
 if ($postarr['post_status'] != 'published') {       
    $data['post_author'] = 45;
 }
  return $data;
}

What am i missing here?

1 Answer 1

1

to know if it's a new post, you juste need to read the value of $postarr["ID"] :

$postType = "post";

add_filter("wp_insert_post_data" . $postType, function ($data, $postarr) {

    if (0 === $postarr["ID"]) { // it's a new post

        $data["post_author"] = 45;

    }


    return $data;


}, 10, 2);
3
  • Wow i never seen that way of adding a filter. Mar 24, 2018 at 19:50
  • I juste have seen I forgot the first line $postType = "post";, I have edited the code. look here for details about anonymous functions php.net/manual/en/functions.anonymous.php
    – mmm
    Mar 24, 2018 at 21:12
  • The check works! Thanks for so much sorry for so little. Mar 24, 2018 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.