반응형
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;
?>
어때요?
<?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
반응형
'source' 카테고리의 다른 글
| MySql 5.7 설치 관리자가 VS 2013 재배포 가능을 감지하지 못함 (0) | 2022.12.11 |
|---|---|
| Java에서 사용되지 않는 가져오기 경고 억제 (0) | 2022.12.11 |
| pip install을 사용한 mariadb 설치 문제 (0) | 2022.12.01 |
| 문자열이 PHP에서 base64인지 확인하는 방법 (0) | 2022.12.01 |
| C에서 텍스트 파일을 읽고 모든 문자열을 인쇄하려면 어떻게 해야 합니까? (0) | 2022.12.01 |