Shortcode to display latest post from one category

Community Forums Forums Design Tips and Tricks Shortcode to display latest post from one category

This topic is: not resolved

Tagged: 

This topic contains 4 replies, has 3 voices, and was last updated by  wyattwerner 2 months, 3 weeks ago.

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #102269

    jodzeee
    Participant
    Post count: 227

    I’m trying to display the most recent post from one category on a page. I thought I’d try to do it without a plugin and I’m close … but where do I define which category?

    function recent_posts_function() {
       query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => 1));
       if (have_posts()) :
          while (have_posts()) : the_post();
             $return_string = '<div class="coupon">'.get_the_content().'</div>';
          endwhile;
       endif;
       wp_reset_query();
       return $return_string;
    }
    
    function register_shortcodes(){
       add_shortcode('recent-posts', 'recent_posts_function');
    }
    
    add_action( 'init', 'register_shortcodes');
    
    #102284

    Sridhar Katakam
    Participant
    Post count: 1049
    #102319

    jodzeee
    Participant
    Post count: 227

    I have a lot of plugins already installed and I’m trying to avoid using another one. Is there another way to create a shortcode in functions.php without using query_posts()?

    #102378

    jodzeee
    Participant
    Post count: 227

    Okay, I think I’ve got it!

    /** Creates shortcode for recent posts */
    
    function recent_posts_shortcode() {
    
    $args = array(
       'category_name' => 'coupons',
       'posts_per_page' => '1',
     );
    $query = new WP_Query($args);
    
    if ( $query->have_posts() ) {
    	while ( $query->have_posts() ) {
    		$query->the_post();
    		return '<div class="coupon">' . get_the_content() . '</div>';
    	}
    } else {
    }
    
    wp_reset_postdata();
    }
    
    function register_shortcodes(){
       add_shortcode('recent-posts', 'recent_posts_shortcode');
    }
    
    add_action( 'init', 'register_shortcodes');

    One issue with it is that if I change the number of posts per page, it doesn’t show more than one. In this case, it doesn’t matter because I only want one, but I’m curious why it doesn’t work. If I use “echo” instead of “return” it does work. However, it also puts the post above my content.

    #116243

    wyattwerner
    Participant
    Post count: 16

    I’m liking this. How do I get the post title to show up?

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.