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.
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 usuallyOBJECT
(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 byname
:Something this.
Use
WP_Query
. This function will retrieve the first post with the given name, ornull
if nothing is found:By default this will search for an item of the type
post
:get_post_by_name("my-post")
As a second argument you can set that to something else:
get_post_by_name("my-page", "page")