WordPress Shortcode Adding Taxonomy Attribute

I have a custom post type for “Staff”. That post type has a taxonomy of “Position” (Doctor, Nurse etc.). I’m trying to create a shortcode that will allow the user to return only staff of a particular taxonomy on the page.

Example:

Read More
  [staff position="doctors"] 

I’ve tried following a few tutorials but can’t seem to get this working. Here is the code I have so far, that returns all staff.

function get_staff($atts) {
$loop = new WP_Query(
    array (
        'post_type' => 'staff',
        'orderby' => 'title'
    )
);

if ($loop->have_posts()) {
    $output = '<div class="staff">';

    while($loop->have_posts()){
        $loop->the_post();
        $meta = get_post_meta(get_the_id());

        $output .= '
            <div class="staff" style="float: left; display: block; border: 1px solid #CCC; margin: 10px; padding: 12px; background-color: #eee;">
                <a href="' . get_permalink() . '">
                    ' . get_the_post_thumbnail($post->ID, 'thumbnail') . '<br />
                ' . get_the_title()  . '</a><br />
                ' . get_the_excerpt() . '
            </div>
        ';
    }
    $output .= "</div>";
} else {
    $output = 'No Staff Added Yet.';
}

return $output;
};

add_shortcode('staff', 'get_staff'); 

Thanks for any help you can offer.

Related posts

Leave a Reply

1 comment

  1. You need to extract the attribute and add it to your query.

    extract( shortcode_atts( array( 'position' => 'doctors' ), $atts ) ); // $position variable will be initialized to 'doctors' if the shortcode is missing the 'position' parameter
    
    $loop = new WP_Query(
        array (
            'post_type' => 'staff',
            'orderby' => 'title',
            'position' => $position
        )
    );