WordPress通过slu query查询单个post
当我想显示一个单独的post,而不使用循环的那一刻,我使用这个:
<?php $post_id = 54; $queried_post = get_post($post_id); echo $queried_post->post_title; ?>
问题是,当我移动网站时,ID通常会改变。 有没有办法通过slu query查询这个职位?
从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 ); }