1

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;
  }
0
0
  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 ):
1
  • Thank you Had1z for pointing out the error in my code. That actually solved my problem. – SoccerZortz Jan 28 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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