반응형
슬러그에 의한 WordPress 쿼리 단일 게시물
루프를 사용하지 않고 단일 게시물을 표시하려는 순간에는 다음을 사용합니다.
<?php
$post_id = 54;
$queried_post = get_post($post_id);
echo $queried_post->post_title; ?>
문제는 내가 사이트를 이동할 때 일반적으로 ID가 변경된다는 것입니다. 슬러그로이 게시물을 조회하는 방법이 있습니까?
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;
?>
어때요?
<?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 );
}
워드 프레스 API가 변경되었으므로 매개 변수 'post_name'과 함께 get_posts를 사용할 수 없습니다. Maartens 기능을 약간 수정했습니다.
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 );
}
참고 URL : https://stackoverflow.com/questions/14979837/wordpress-query-single-post-by-slug
반응형
'Development Tip' 카테고리의 다른 글
WPF에서 타이머를 어떻게 생성합니까? (0) | 2020.11.03 |
---|---|
공백으로 문자열을 분할하고 정규 표현식을 사용하여 선행 및 후행 공백을 단어 배열로 무시하는 방법은 무엇입니까? (0) | 2020.11.03 |
자바 스크립트 확장 클래스 (0) | 2020.11.03 |
"IIS Express 웹 서버를 시작할 수 없습니다." (0) | 2020.11.03 |
.NET 소스 코드가 디버깅 중단 점을 하드 코딩 할 수 있습니까? (0) | 2020.11.03 |