NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Intermediate

---- Last modified : Sep 09 2022

Estimated reading time : 1 minute, 29 seconds - 96 words

With this tutorial, we will create a shortcode that will return the results of a WordPress query.

We will be creating a add_shortcode shortcode that will contain the shortcode name and function as parameters.
With this example, we will call a query for a Video post type sorted by number of likes.

We edited the get option inside the shortcode if you have options. Then we run the new WP_Query.

<?php
// Creation du shortcode permettant de lister la liste des videos classées par nombre de likes
add_shortcode( 'viavideoslikes', 'via_videos_list_likes_shortcode' );
function via_videos_list_likes_shortcode( $atts ) {
	ob_start();
	$options = get_option('via_video_name');
	$query = new WP_Query( array(
		'post_type'            => 'viavideos',
		'meta_key'             => '_post_like_count',
		'orderby'              => 'meta_value_num',
        'order'                => 'DESC',
		'posts_per_page'       => -1,
		) );
	if ( $query-&gt;have_posts() ) { 
	?>
	
	
	<?php while ( $query->have_posts() ) : $query->the_post(); ?>

	
        // Afficher ici votre contenu dynamique dans vos contenants div


	<?php endwhile; wp_reset_postdata(); ?>
	<?php $myvariable = ob_get_clean();
	return $myvariable;
	}
}

Creating a Query Post Shortcode for WordPress

[viavideoslikes]

Or in a template page

<?php echo do_shortcode('[viavideoslikes]'); ?>

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>