Can’t get post ID in functions.php?

The post ID is available after the query has been fired.

The first hook that is safe to get post id is 'template_redirect'.

If you can modify your function to accept a post id as argument, like so:

function em_change_form($id){
    $reg_type = filter_input(INPUT_GET, 'reg_typ', FILTER_SANITIZE_STRING);
    if($reg_type === 'vln'){
      update_post_meta($id,'custom_booking_form', 2);
    } elseif ($reg_type == 'rsvp') {
      update_post_meta($id,'custom_booking_form', 1);
    }
}

You can do:

add_action('template_redirect', function() {
  if (is_single())
     em_change_form(get_queried_object_id());
  }
});

I’ve used get_queried_object_id() to obtain current queried post id.

If you absolutely need to call your function on an early hook like 'init', you can use url_to_postid(), and home_url() + add_query_arg() to obtain current url:

add_action('init', function() {
  $url = home_url(add_query_arg(array()));
  $id = url_to_postid($url);
  if ($id) {
     em_change_form($id);
  }
});

Note that second method is less performant because url_to_postid() forces WordPress to parse rewrite rules, so if you can, use the first method.

Leave a Comment