• Hey guys,

    I’ve been stuck with this for days.

    How can I show a particular category’s posts on a page?

    I want my page in navigation menu named ‘exercise’ show excerpts of posts from exercise category.

Viewing 1 replies (of 1 total)
  • if you want to show posts in a category on a page, you can follow the instructions bellow.

    1. copy and past bellow code in the functions.php file in your theme.

    <?php
    function unc_show_posts_by_category($attr){
        /** wp query to get posts from specific category */
        $cat_name = $attr['category_name'];
        $num_posts = $attr['num_posts'];
        $unc_query = new WP_Query( array('category_name' => $cat_name, 'posts_per_page' => $num_posts));
    
        $results = '';
        /** starting the loop */
        if($unc_query->have_posts()):
            $results .= '<ul class="muaw-posts-by-category">';
            while($unc_query->have_posts()){
                $unc_query->the_post();
                $results .= '<li>';
                if(has_post_thumbnail()) {
                    $results .= '<a href="' . get_the_permalink() . '" rel="bookmark">' . get_the_post_thumbnail(get_the_ID(), array(50, 50)) . get_the_title() . '</a>';
                } else {
                    $results .= '<a href="' . get_the_permalink() . '" rel="bookmark">' .get_the_title() . '</a>';
                    $results .= get_the_excerpt();
                }
                $results .= '</li>';
            }
            $results .= '</ul>';
        endif;
    
        return $results;
    
        /* Re-set original Post Data */
        wp_reset_postdata();
    }
    
    // Add a shortcode
    add_shortcode('muaw_category_posts', 'unc_show_posts_by_category');
    ?>

    2. Add bellow shortcode with category name and number of posts.
    [muaw_category_posts category_name="uncategorized" num_posts="5"]

    That’s it. This code is used for one of my theme, so feel free to make necessary adjustments.

Viewing 1 replies (of 1 total)
  • The topic ‘Show category posts’ is closed to new replies.