0

I have a recent post shortcode to display a custom post. Everything works fine so far. However, I would like to add a category attribute so I can specify which category to display.

My working code is as follows:

function my_recent_posts_shortcode2( $atts ) {
    extract( shortcode_atts( array( 'limit' => 7, 'type' => 'g1_event'), $atts ) );

    global $paged;
    $q = new WP_Query(  array ( 
        'posts_per_page' => $limit, 
        'post_type' => $type, 
        "orderby" => 'meta_value',
        "meta_key" => 'evt_start_date',
        "order" => 'ASC',
        'paged' => $paged 
    ) );

    $list = '<ul class="recent-events">';

    while ( $q->have_posts() ) {
        $q->the_post();

        //for this post, get custom field "event_date" which should be in yyyy-mm-dd format and display as to month, day
        //2011-02-22 will display as February 22
        $evt_start_date = get_post_meta($post->ID, 'evt_start_date', true);
        $evt_start_date = get_post_meta($post->ID, 'evt_start_date', true);
        if ($evt_start_date) {
            echo 'The event date is '. date('F j', strtotime($evt_start_date));
        }

        $list .= '<li>' . '<a href="' . get_permalink() . '">' . get_the_title() . '</a>' . '<br>'. get_post_meta( get_the_ID(), 'evt_start_date', true ) . ' @ ' . get_post_meta( get_the_ID(), 'evt_location', true ) . '</li>';
    }

    wp_reset_query();

    return $list . '</ul>';
}
add_shortcode( 'recent-events', 'my_recent_posts_shortcode2' );

Right now I place the shortcode using: [recent-events][/recent-events]

I would like to be able to specify the category ID: [recent-events cat="62"][/recent-events]

Hope this is clear, thank you.

1 Answer 1

0

Add the category parameter:

shortcode_atts( array(
    'limit' => 7,
    'type'  => 'g1_event',
    'category' => '',
), $atts);

In your WP_Query add:

'category_name' = $category

For your shortcode use:

[recent-events category="slugName"]
1
  • 1
    Never ever use extract(). It uses eval() which poses serious security risks. Dec 2, 2014 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.