How to get current post_id in function.php file

前端 未结 3 2052
时光说笑
时光说笑 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 19:57

    Here is one my function what never fail.

    I don't know why WordPress not made something like this before.

    /**
        * Get current page ID
        * @autor    Ivijan-Stefan Stipic
        * @version  1.0.0
        **/
        function get_current_page_ID(){
            global $post, $wp_query;
            
            if(!is_null($wp_query) && isset($wp_query->post) && isset($wp_query->post->ID) && !empty($wp_query->post->ID))
                return $wp_query->post->ID;
            else if(function_exists('get_the_id') && !empty(get_the_id()))
                return get_the_id();
            else if(!is_null($post) && isset($post->ID) && !empty($post->ID))
                return $post->ID;
            else if('page' == get_option( 'show_on_front' ) && !empty(get_option( 'page_for_posts' )))
                return get_option( 'page_for_posts' );
            else if((is_home() || is_front_page()) && !empty(get_queried_object_id()))
                return get_queried_object_id();
            else if($this->get('action') == 'edit' &&  && isset($_GET['post']) && !empty($_GET['post']))
                return absint($_GET['post']);
            else if(!is_admin() && isset($_GET['p']) && !empty($_GET['p']))
                return absint($_GET['p']);
            
            return false;
        }
    

    This function check all possible cases and return ID of the current page or false on the fail.

提交回复
热议问题