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; }
Great article, thank You !!
Thanks for sharing information. I really appreciate it
Helped me tremendously! Thanks!