Get post id in a function when edit/add a post

I am new to PHP and I am working in WordPress. I wrote a function in the functions.php file. My function is to update a custom field based on another field on the page when the user adds or edits a post. I am having trouble getting the post id in my function. How can I get the Post Id? What am I doing wrong?

Here is my function:

  function get_postid() {
    global $post;
    $id = $post->ID;
  }

  add_action( 'admin_notices', 'get_postid' );

  function set_post_sort_order() {
    /* Get post id */
    $post_id = get_postid();

    
    /* Does object exist */
    if ( !$post_id ):

        /* Get which product taxonomy is selected. */
        $terms = get_the_terms( $post_id, 'product' );
        $sort_order = 2;

        if ( ! empty( $terms ) ) :
          foreach( $terms as $term ) {
            if ( $term->name == 'blah blah' ) :
                $sort_order = 1;
            endif;

            update_post_meta( $post_id, 'post_order', $sort_order );
          } 
        endif;

    endif;
  }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

  1. Your function get_postid() does not return anything. It should return the id:
function get_postid() {
    global $post;
    return $post->ID; 
}
  1. If you are going to use the $post_id I guess your first if statement is wrong, because the $post_id should be evaluated to true not false. So it should be like this: if ( $post_id ):


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x