Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current post_id in function.php file

Tags:

wordpress

This is my function in function.php file

  function getcity(){
    global $wpdb;

    if($_POST['state'])
            {
                $id=$_POST['state'];
                $district = get_post_meta(get_the_ID() , 'district', true);

                                     var_dump($district);
                $result=$wpdb->get_results("SELECT * FROM districts WHERE state_id='$id'");

                                                       foreach($result as $row) {
                                                             $district_name   = $row-
  >district_name;
                             $district_id     = $row->district_id;

                            echo '<option value="'.$district_id.'">'.$district_name.'</option>';


            }
     }
   }
 add_action("wp_ajax_nopriv_getcity", "getcity");
 add_action("wp_ajax_getcity", "getcity");

I want to get current post id in this function to display selected dropdown value..

like image 415
Kedar B Avatar asked Sep 14 '25 21:09

Kedar B


1 Answers

Note that $post or get_queried_object_id() do not work until the first query was fired. So these options are available only at the hook template_redirect and later. But functions.php is included much earlier (before the hook after_setup_theme) so this isn't a solution.

A function that should work pretty much anywhere would be:

$url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . $_SERVER[ 'REQUEST_URI' ];
$current_post_id = url_to_postid( $url );

Here is a overview over hook execution order.

As mentioned in the comments url_to_postid may be heavy in some setups, so if your code is executed after template_redirect you better use one of the solutions below as they are most likely much faster than the snippet above:

global $post;
$id = $post->id;

or

$id = get_queried_object_id();
like image 75
GDY Avatar answered Sep 17 '25 19:09

GDY