I’d like to show you how to choose a random quote from the quotes custom post type I showed you how to create in this post.
In my last post, I showed you how to create a basic WordPress Shortcode.
We must first query the database for the custom post type:
function random_quote_func( $atts ){ $args=array( 'orderby'=> 'rand', 'post_type' => 'quote', 'post_status' => 'publish', 'posts_per_page' => 1, ); $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().'</blockquote>'; endwhile; } wp_reset_query(); return $message; } add_shortcode( 'random-quote', 'random_quote_func' );
I add that code to the WordPress functions.php file and then add the shortcode to a WordPress page or post like this:
[[random-quote]]
You can see the results of this code on my site: ourprosperouslife.com
Each time you refresh the page, you will see a random quote.
Pingback: Pass a Variable to a WordPress Shortcode - Cullen Web Services
Pingback: Post Something to a Facebook Page I Manage From My WordPress Site - Cullen Web Services