0

I need to get the last 2 posts from News Category and show them in sidebar. I use the code below

<?php $news_id = get_cat_ID('News');
    if($news_id) {
        echo '<div class="entry-title"><a href="'.get_category_link( $news_id ).'">'.get_the_category_by_ID( $news_id ).'</a></div>'; 

        $recent_news = wp_get_recent_posts( array('numberposts' => 2, 'category' => $news_id, 'post_status' => 'publish'));

        if ($recent_news) {
            echo '<ul class="sidebar-posts-list">';
            foreach ($recent_news as $news_item) {
                echo '<li><div class="item-title">' .  $news_item["post_title"].'</div>';
                echo '<div class="item-text">' . wp_trim_words( $news_item["post_content"], 20 ) . '</div>';            
                echo '<a href="' . get_permalink($news_item["ID"]) . '" class="read-more">Read more</a></li>';  
            }
            echo '</ul>';
        }
}?>

but I'm not sure that using wp_trim_words( $news_item["post_content"], 20 ) is the right way to get what I want. It works but I'm not sure it's right. Maybe there is a better way to do that?

0

One potential issue I see with that is if the content contains Shortcodes.

You can strip Shortcodes before passing it to wp_trim_words if you want them removed, or alternately, if you want to maintain them you can apply the Shortcodes beforehand.

You may also want to check that $news_item["post_excerpt"] is not empty, in case a custom excerpt has been entered in place of your auto-trimmed version.

  • So, can I just add strip_shortcodes function in my code like wp_trim_words( strip_shortcodes ($news_item["post_content"]), 20 )? Will it be enough for correct work? And I don't undestand why, but my $news_item["post_excerpt"] is empty in every $news_item. – hronikata Sep 12 '15 at 18:00
  • Yes, that will work. post_excerpt will be empty unless you manually create an excerpt in the Excerpt field when editing a post. The field may be hidden on your post edit screen, click the Screen Options tab in the upper right corner and tick the Excerpt box to see it. – Milo Sep 12 '15 at 18:08
  • Thanks a lot for the answer and the explanation. I think, I don't need post_excerpt here, I think, using wp_trim_words( strip_shortcodes ($news_item["post_content"]), 20 ) will be enough for me. – hronikata Sep 12 '15 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.