WordPress query single post by slug

前端 未结 4 824
情书的邮戳
情书的邮戳 2020-12-25 09:24

For the moment when I want to show a single post without using a loop I use this:



        
4条回答
  •  独厮守ぢ
    2020-12-25 09:52

    As wordpress api has changed, you can´t use get_posts with param 'post_name'. I´ve modified Maartens function a bit:

    function get_post_id_by_slug( $slug, $post_type = "post" ) {
        $query = new WP_Query(
            array(
                'name'   => $slug,
                'post_type'   => $post_type,
                'numberposts' => 1,
                'fields'      => 'ids',
            ) );
        $posts = $query->get_posts();
        return array_shift( $posts );
    }
    

提交回复
热议问题