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.
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.
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: <?
Bookmark this question. Show activity on this post. $page = get_page_by_path("page-slug", OBJECT, 'page');
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'.
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With