Create a wordpress Shortcode to display category posts

Here is what I have so far. I’m in no way a great programmer. Just a front end guy trying to get this to work. I have a website with different blog categories. For example I have a category called: foods, places, things. I’m trying to write a function where I can execute a shortcode like this:

[list_post mycat=”foods”]

Read More

Basically I want it to be flexible so whatever category I put inside of “mycat” it will display those blogs.

Again any help would be really appreciated. I know I need to pass a parameter, but I’m honestly unsure how. This is my best effort. Thanks for any hekp

    $args = array(
    //Pass parameter here
    //Something like array (
        //$mycat => 'slug';
    //);

    );

function list_post($mycat){


    $query = new WP_Query(array('category_name' => $mycat));
    if($query->have_posts()):
        while($query->have_posts()):the_post();
            the_title();
        endwhile;
    else:
        echo "No posts found!";
    endif;
    wp_reset_postdata();
}

add_shortcode('list_post', 'list_post')

Related posts

2 comments

  1. Your shortcode accepts 1 argument and it’s an array with values inside of it. So for this case, $mycat looks like this => array('mycat' => 'foods');, So for this instance, you should use the following to extract and compare:

    function list_post($atts){
        $arr = shortcode_atts( array(
            'mycat' => 'some_default_category',
        ), $atts );
        //now you can call $arr['mycat']; instead of $mycat.
    }
    
  2. Its easier to use get_posts() to achieve this.

    function list_post($atts){
        $arr = shortcode_atts(
            array(
                'mycat' => 'slug',
            ), $atts );
    
        $args = array('category_name' => $arr['mycat']);
        $out = '';
        $posts = get_posts($args);
        if ($posts){
            foreach ($posts as $post) {
                $out .= $post->post_title . '<br />';
            }
        }
        else {
            $out .= 'No posts found!';
        }
        return $out;
    
    }
    
    add_shortcode('list_post', 'list_post');
    

    Note that it is better to return the output from your shortcode and not echo it.

    Edit: Removed usage of extract() function as per @PieterGoosen’s advice.

Comments are closed.