WordPress query single post by slug

前端 未结 4 820
情书的邮戳
情书的邮戳 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:44

    From the WordPress Codex:

    <?php
    $the_slug = 'my_slug';
    $args = array(
      'name'        => $the_slug,
      'post_type'   => 'post',
      'post_status' => 'publish',
      'numberposts' => 1
    );
    $my_posts = get_posts($args);
    if( $my_posts ) :
      echo 'ID on the first post found ' . $my_posts[0]->ID;
    endif;
    ?>
    

    WordPress Codex Get Posts

    0 讨论(0)
  • 2020-12-25 09:45

    How about?

    <?php
       $queried_post = get_page_by_path('my_slug',OBJECT,'post');
    ?>
    
    0 讨论(0)
  • 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 );
    }
    
    0 讨论(0)
  • 2020-12-25 10:05

    a less expensive and reusable method

    function get_post_id_by_name( $post_name, $post_type = 'post' )
    {
        $post_ids = get_posts(array
        (
            'post_name'   => $post_name,
            'post_type'   => $post_type,
            'numberposts' => 1,
            'fields' => 'ids'
        ));
    
        return array_shift( $post_ids );
    }
    
    0 讨论(0)
提交回复
热议问题