Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get post by post name instead of id

Tags:

php

wordpress

Ok i have this code currently.

<?php

$post_id = 266;
echo "<div id='widgets-wrapper3'><div id='marginwidgets' style='overflow: auto; max-    width: 100%; margin: 0 auto; border: none !important;'>";
$queried_post = get_post($post_id); 
echo "<div class='thewidgets'>";
echo substr($queried_post->post_content, 0, 500);
echo "<a href='".get_permalink( 26 )."' title='Read the whole post' class='rm'>Read     More</a>";
echo "</div>";

echo "</div></div>";

?>

As you can see to the above code, the routine is to get the post by ID, but my permalinks change into post name instead of post id for SEO purposes. How do I get the post by post name?

Hope someone here could figure it out. Thank you.

like image 259
Juliver Galleto Avatar asked Oct 16 '12 00:10

Juliver Galleto


People also ask

How do I get post title by id?

Another function to display a post title by ID To use get_post, the object that references a function has to be set. That object is able to retrieve all members of the get_post. To get the title of the post by ID using this function, you will use the member variable post_title.

How do I get post by name in WordPress?

To get a post, rather than a page, you just need to supply 'post' as the $post_type argument, and usually OBJECT (with no quotes) as the $output type, like this: <?

How do I find slug Post ID?

Bookmark this question. Show activity on this post. $page = get_page_by_path("page-slug", OBJECT, 'page');


1 Answers

get_page_by_path()

WordPress has a built-in function that might help, with a few words of caution.

<?php get_page_by_path( $page_path, $output, $post_type ) ?>

Here's the relevant Codex entry.

To get a post, rather than a page, you just need to supply 'post' as the $post_type argument, and usually OBJECT (with no quotes) as the $output type, like this:

<?php get_page_by_path( 'my_post_slug', OBJECT, 'post' ) ?>

Note this function does not check the published or private status of the matched post. This is great if the item you're looking for is and attachment, but can be problematic for posts and pages (ie drafts, private posts etc.)

Note if it is a page you're looking for, and that page is hierarchical (ie: it has a parent), then you need to supply the entire path, that is: 'parent_page_slug/my_page_slug'.

WP_Query / get_posts()

If either of these are a problem for you, then you should consider just using the WP_Query class to get your post by name:

$found_post = null;

if ( $posts = get_posts( array( 
    'name' => 'my_post_slug', 
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1
) ) ) $found_post = $posts[0];

// Now, we can do something with $found_post
if ( ! is_null( $found_post ) ){
    // do something with the post...
}
like image 120
Tom Auger Avatar answered Oct 21 '22 21:10

Tom Auger