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]' );
This functions takes parameter for how many recent posts you want to display.
Ex : you want to display only five recent posts. Just passed the arguments with posts="5" (you can pass any number of recent posts that you want to display).
Function fetch only five recent posts from database.
// recent-posts is going to be our shortcode.
add_shortcode('recent-posts', 'recent_posts_function');
// Functions takes parameter such as posts="5".
function recent_posts_function($atts){
extract(shortcode_atts(array(
'posts' => 1,
), $atts));
$return_string = '<ul>';
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
endif;
$return_string .= '</ul>';
wp_reset_query();
return $return_string;
}
Eg. echo do_shortcode( '[recent-posts posts="5"]' );
add_shortcode( $tag , $func );
Parameter | Details |
---|---|
$tag | (string) (required) Shortcode tag to be searched in post content |
$func | (callable) (required) Hook to run when shortcode is found |