Forums

Tags In Page (2 posts)

  1. FordRacer2007
    Member
    Posted 5 months ago #

    Ok, thanks in advance to anyone that helps, I already ran a search before I posted and turned out with nothing.

    I created a page on my website, in that page I would like to be able to display just 1 latest post of a specific TAG that I choose. What code do I need to enter while on "Edit Page" to accomplish this?

    I've looked for plugins also, but have only found some that display posts based on tag on the sidebar, and that's not what I'm looking for.

  2. vtxyzzy
    Member
    Posted 5 months ago #

    You might be able to use a shortcode. Here is some sample code that you can modify to output the post the way you prefer:

    function get_one_post_by_tag($atts) {
       // Get a single post given a tag slug
       // [tag_post tag_slug='the-slug']
       extract(shortcode_atts(array('tag_slug' => 'tagit'),$atts));
       $args = array(
          'caller_get_posts' => 1,
          'posts_per_page' => 1,
          'tag' => $tag_slug,
       );
       $tag_query = new WP_Query($args);
       ob_start();
       if ($tag_query->have_posts()) {
          while ($tag_query->have_posts()) {
             $tag_query->the_post();
             // Alter the output below as you prefer
             the_title();
             the_content();
          }
       } else {
          echo "Sorry, no Posts were found for $tag_slug";
       }
       $op = ob_get_clean();
       return $op;
    }
    add_shortcode('tag_post','get_one_post_by_tag');

    Add the code above to your functions.php. Be careful though, any errors will make the site unusable. Depending on your theme, you may need to enclose the code in opening and closing php tags.

    Then, in your page code the shortcode like this:

    [tag_post tag_slug="the-slug"]

Reply

You must log in to post.

About this Topic

Tags