How to Pass a Variable to a WordPress Shortcode

Random Quote Generator

In order for me to choose how many quotes I want to display with my random quote generator, I need to be able to pass a variable to the shortcode I built in my last post. I may need 2 or 3 quotes instead of just one quote depending on where my shortcode is used.

To start the process we use the WordPress shortcode_atts function. According to the WordPress codex, this function ‘combines user shortcode attributes with known attributes and fills in defaults when needed.


The result will contain every key from the known attributes, merged with values from shortcode attributes.’ Then we use the php extract function to put those attributes in variables

extract( shortcode_atts( array(
  'number' => 1,
), $atts ) );

This sets up a variable named ‘number’ and sets the default to 1. If a variable is passed in the shortcode like this:

[random-quote number="3"]

Then after our shortcode_atts() and extract() functions, we will have $number set to 3. If, however, we use the shortcode like this:

[random-quote]

The $number variable will be set to the default which we set to 1 in the code above.

We can set the number argument of the wp-query with our new shortcode variable in the args array:

$args=array(
  'orderby'=> 'rand',
  'post_type' => 'quote',
  'post_status' => 'publish',
  'posts_per_page' => $number,
);

So, now we can use the new code above integrated with the code from the last post about shortcodes.

function random_quote_func( $atts ){
    extract( shortcode_atts( array(
        'number' => 1,
    ), $atts ) );
    $args=array(
        'orderby'=> 'rand',
        'post_type' => 'quote',
        'post_status' => 'publish',
        'posts_per_page' => $number,
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    $message = '';
    if( $my_query->have_posts() ) {
        while ($my_query->have_posts()) : $my_query->the_post(); 
            $message .= '<blockquote>'.get_the_content();
            if ($show_by == 'ON') {
    	        $message .= '<cite>'.get_post_meta(get_the_ID(), 'cc_by', true).'</cite>';
            }
            $message .= '</blockquote>';
         endwhile;
     }
     wp_reset_query();  
     return $message;
}


3 thoughts on “How to Pass a Variable to a WordPress Shortcode”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top