如何使用WordPress中的帖子名称和类别名称获取帖子ID?

时间:2017-05-31 16:10:42

标签: wordpress

如何使用WordPress中的帖子名称和类别名称来获取帖子ID?

我使用过此代码,但对我没用。

$post_slug = get_post_field( $post_name, get_post() ); 
$args = array(
'name'        => $post_slug,
'category_name' => $pcat_name,
'post_type'   => 'post',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
if( $my_posts ) :
$rid=$my_posts[0]->ID;
endif;
这个slu is不行。

我想检查帖子名称和必须的类别名称。

1 个答案:

答案 0 :(得分:0)

您可以使用get_page_by_title()(https://codex.wordpress.org/Function_Reference/get_page_by_title)来获取帖子或任何其他帖子类型:

$posts = get_page_by_title($post_name, OBJECT, 'post');
foreach($posts as $post){
    if(in_category($pcat_name, $post->ID)){
        echo $post->ID;
    };
};
相关问题