Forums

[resolved] shortcode - display post by name (3 posts)

  1. dangle2k
    Member
    Posted 11 months ago #

    I'd like to create a page of featured posts not based by category or tags but by the posts name. I assume that using a shortcode would be the best way for someone to easily display a few featured posts, kind of like so:

    [featuredpost post="my favorite post title"]
    [featuredpost post="my second favorite post title"]

    I've looked around for something to use and all I can find are shortcodes for listing posts by category or tags or something similar. I've tried to modify a list post by category shortcode by basically changing "category_name" to "post_name" like the example below:

    function post_listing_shortcode($atts) {
        extract(shortcode_atts(array(
            'post' => '',
            'include_date' => '',
        ), $atts));
    
        $args = array(
            'post_name' => $post,
        );
    
        $return = '';
        $listing = new WP_Query($args);
        if ($listing->have_posts()):
            $return .= '<ul>';
    
            while ($listing->have_posts()): $listing->the_post(); global $post;
                $return .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a>';
                if ($include_date) $return .= ' ('.get_the_date('n/j/Y').')';
                $return .= '</li>';
            endwhile;
    
            $return .= '</ul>';
        endif; wp_reset_query();
    
        if (!empty($return)) return $return;
    }
    add_shortcode('listing', 'post_listing_shortcode');

    obviously that doesn't work. Can someone please give me some help on accomplishing this? Ultimately I'd like to have the desired posts listed with the post title, author, excerpt and category along with the post thumbnail, but first things first. If I can just get some help getting a shortcode that displays a post by the posts name that would be a great start.

    Or would there be a better way than using a shortcode?

    Thank you.

  2. MichaelH
    Volunteer
    Posted 11 months ago #

    According to http://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters how about using the post slug with this change:

    $args = array(
            'name' => $post,
        );
  3. dangle2k
    Member
    Posted 11 months ago #

    Yup, that did the trick! Just 'name' not 'post_name'.

    Thank you very much for your help!

Reply

You must log in to post.

About this Topic