Richard McDougall
Richard McDougall

Reputation: 3

Wordpress post summary PHP show excerpt

first question from a total newby. I want to display the 12 most recent post titles, images, excerpts, author, date & time published, excluding certain categories, on the home page of our website - http://www.yorkmix.com. Essentially like the standard category pages do now - see http://www.yorkmix.com/category/opinion

For various reasons, I want to put it in as a php widget and the site is set up for that. The code below shows the correct headlines and photos but when I add excerpt code it just shows the same excerpt over and over along with the same image. I would like to retain control over the styling in a way the excerpt and photo don't appear to allow.

Thanks for your help.

<?php

include($_SERVER['DOCUMENT_ROOT'] . $root . 'blog/wp-load.php');

$recent_posts = wp_get_recent_posts(array(
    'numberposts' => 12, 
    'category__not_in' => array(109,117),
    'post_status' => 'publish'
));

?>

<ul class="listing">
<?php foreach($recent_posts as $post) : ?>
    <li>
        <a href="<?php echo get_permalink($post['ID']) ?>">
            <?php echo get_the_post_thumbnail($post['ID'], 'thumbnail'); ?>
            <div><h2><?php echo $post['post_title'] ?></h2></div>
        </a>
    </li>
<?php endforeach; ?> 
</ul>

Upvotes: 0

Views: 1269

Answers (2)

Naty
Naty

Reputation: 595

inside your 'for each' loop use : $postObject = get_post($post['ID']); than use post_excerpt field, like : echo $postObject->post_excerpt; so it should look like this :

<?php foreach($recent_posts as $post){
$postObject = get_post($post['ID']);
?>
<li>
<?=$postObject->post_excerpt?>
...

Upvotes: 0

SidFerreira
SidFerreira

Reputation: 578

Welcome to Wordpress development and yes, this is a common problem for newbies. I had it too.

To keep the code, you could just use $post['post_excerpt'];

But, Wordpress uses a different logic named "The Loop", and you should try to keep using that:

$query_recent = new WP_Query(array(
    'numberposts' => 12, //The default is 10
    'category__not_in' => array(109,117),
    'post_status' => 'publish', //The default is publish already
    'post_type' => array('post', 'page') //could use only a string 'any' too
));

while($query_recent->have_posts()) {
    $query_recent->the_post();
?>
    <li>
        <a href="<?php the_permalink() ?>">
            <?php the_post_thumbnail('thumbnail'); ?>
            <div><h2><?php the_title() ?></h2> <?php the_excerpt(); ?></div>
        </a>
    </li>
<?php
}

With the loop, a global variable is set and you can use simple functions without the post ID. Check this out and you will improve your code and understand plugins :)

Upvotes: 3

Related Questions