add_shortcode
is wp keyword.
// recent-posts is going to be our shortcode.
add_shortcode('recent-posts', 'recent_posts_function');
// This function is taking action when recent post shortcode is called.
function recent_posts_function() {
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string = '<a href="'.get_permalink().'">'.get_the_title().'</a>';
endwhile;
endif;
wp_reset_query();
return $return_string;
}
This snippet can be placed in your theme functions.php
.
[recent-posts]
This is out shortcode for recent post. We can apply this shortcode in backend (such as pages, post, widgets ).
We can also used same shortcode inside our code. with the help of do_shortcode
.
Eg. echo do_shortcode( '[recent-posts]' );