Blog

How t create a WordPress Short Code to display latest post from a post type

Its not very hard to create a short code. WordPress have inbuilt api to create shortcode. We are mainly using add_shortcode  function to create a short code in wordpress. The usage of this function is

add_shortcode('ApartmentList', 'recent_appartment_function');

Where the ApartmentList is the short code we are using inside our pages or posts we can use it like [ApartmentList] In this post we are are explaining how to create a short code for display latest 3 post from a post type called Appartment

The code is as follow:

<?php

function recent_appartment_function() {
global $post;

$html = "";

$my_query = new WP_Query( array(
'post_type' => 'appartment',
'posts_per_page' => 3
));

if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();

$html .= "<div class='appartment_entry'>";
$html .= "<div class='appapertment_image'>" .get_the_post_thumbnail() . "</div>";

$html .= "<h2>" . get_the_title() . " </h2>";

$html .= "<a href=\"" . get_permalink() . "\" class=\"button\">Read more</a>";

$html .= "</div>";
endwhile;
wp_reset_postdata();
endif;

return $html;
}

function register_shortcodes(){
add_shortcode('ApartmentList', 'recent_appartment_function');
}
add_action( 'init', 'register_shortcodes');

?>

This code will display latest 3 apartment from post type with image. You can modify the code as per your required. The end result is