source

WordPress 쿼리 슬러그별 한 포스트

itover 2022. 12. 11. 10:17
반응형

WordPress 쿼리 슬러그별 한 포스트

루프를 사용하지 않고 하나의 투고를 표시하고 싶을 때는 다음을 사용합니다.

<?php
$post_id = 54;
$queried_post = get_post($post_id);
echo $queried_post->post_title; ?>

문제는 사이트를 옮기면 보통 아이디가 바뀐다는 거예요.이 게시물을 slug로 조회할 수 있는 방법이 있나요?

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 게시물 가져오기

어때요?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

저렴한 재사용 방법

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 );
}

wordpress api가 변경되었기 때문에 param 'post_name'에는 get_posts를 사용할 수 없습니다.Martens 함수를 조금 수정했습니다.

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 );
}
<?php    
$page = get_page_by_path('slug', ARRAY_N);
echo $page->post_content

function get_id_by_slug($page_slug) {
      $page = get_page_by_path($page_slug, ARRAY_N);
      if ($page[0] > 0) {
        return $page[0];
      }else{
        return null;
      }
}

언급URL : https://stackoverflow.com/questions/14979837/wordpress-query-single-post-by-slug

반응형