How to get post by slug in Wordpress?

22:19
1845
-
Like this post? Rate it:
Hello guys! I need to get WP post ID by its slug. Is it possible? If so, can anybody help me with function?
Related CMS:
RSS
22:21
Hi Tony. The easiest way to get post ID by slug:
 
<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>
 

Also, maybe recommendation from Codex will be helpful for you:
 
<?php
$the_slug = 'my-slug';
$args = array(
	'name'           => $the_slug,
	'post_type'      => 'post',
	'post_status'    => 'publish',
	'posts_per_page' => 1
);
$my_posts = get_posts( $args );
if( $my_posts ) {
	echo 'ID on the first post found ' . $my_posts[0]->ID;
}
?>
 

BTW, why you need to get post ID by slug?
Zahid Hossain
12:24
But i get error when i use get_page_by_path() with WP_Query. Because get_page_by_path() first and required parameter is string and WP_Query is an object.
my code is below. And i get error while i use below code in a class:
Catchable fatal error: Object of class WP_Query could not be converted to string in C:\wamp\www\wordpress-theme-test\wp-includes\post.php on line 4470

$pages = array( 'member-login', 'member-account', 'member-register', 'member-password-lost', 'member-password-reset' );

foreach ( $pages as $slug ) {
$query = new WP_Query( 'pagename='. $slug );

$page = get_page_by_path( $query );
wp_delete_post( $page->ID, true );
}

I there any way to solve it???
Loading...