How to get current post_id in function.php file

前端 未结 3 2060
时光说笑
时光说笑 2021-01-06 19:28

This is my function in function.php file

  function getcity(){
    global $wpdb;

    if($_POST[\'state\'])
            {
                $id=$_POST[\'state\         


        
3条回答
  •  滥情空心
    2021-01-06 20:11

    Note that $post or get_queried_object_id() do not work until the first query was fired. So this 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.

    If your code is executed after the template_redirect hook these option may be better:

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

    or

    $id = get_queried_object_id();
    

提交回复
热议问题