I’m trying to get post excerpt and title by specific post ID.
My post ID is 6 and my code as follows
<?php
$id = 6;
$post = get_post( $id );
$excerpt = get_excerpt( $id);
$excerpt = $post->post_excerpt;
?>
<h6><?php the_title(); ?></h6>
<?php echo get_excerpt(190); ?>
It shows the title of post ID 6, but the wrong excerpt…
Also I’ve an excerpt length control code in my functions.php
// Changing excerpt length
function get_excerpt($count){
$permalink = get_permalink($post->ID);
$excerpt = get_the_content();
$excerpt = strip_tags($excerpt);
$excerpt = substr($excerpt, 0, $count);
$excerpt = substr($excerpt, 0, strripos($excerpt, " "));
$excerpt = $excerpt.'... <a href="'.$permalink.'">Read More</a>';
return $excerpt;
}
Any help will be appreciated…
Your
get_excerpt()
function uses theglobal
$post
variable, which is out of scope inside your function.That means that when you do this:
You are attempting to get the post content for the current post in the Loop truncated based on the ID of the post whose excerpt you are trying to get, but
$post
would be out of scope and thus “undefined”. Then, assuming$post
were set,…… you are then completely overwriting that generated “excerpt” data with the raw excerpt data from the current post in the Loop.
And then…
… you grab the excerpt from the current post in the Loop again, and echo it.
What you are doing is quite wrong in several different ways. I have to assume that you’ve copied and pasted that code without understanding it, which is quite dangerous. I’d caution you against it.
The WordPress Core function
get_the_title()
will accept an ID argument, butget_the_excerpt()
will not, so since you need both you are going to be best off simply retrieving the post object.The generate an excerpt from post content, you’d need something like:
Which is really just a simplified version of the Core function
wp_trim_excerpt()
You can control the length of the excerpt using the
excerpt_length
filter. Per the example in the Codex:<?php echo get_excerpt(190); ?>
this part is wrong. You are printing excerpt fromid = 190
just useecho $excerpt
. Also you don’t need the line<?php echo get_excerpt(190); ?>
Read the codex pages carefully you will see lots of helpful examples there to understand how a function works http://codex.wordpress.org/Function_Reference/get_post
It looks like you’ve got a lot happening…
I’d try the following:
And use the following to display the excerpt:
Why don’t you echo $excerpt variable?
I think this should work.
Don’t do this:
do this:
If you want to get the expert of a specific post with id 6, you can simply do as follow:
This will simply give the title and the excerpt of the post with id 6.