[wd_asp elements=’search’ ratio=’100%’ id=1]

Shortcodes – a simple tutorial

5th August 2013

Wordpress - Miscellaneous

wordpress category

WHY: Shortcodes enable you to use PHP in your posts and pages.

Shortcodes are very easy to learn, but you will not find such an easy to learn tutorial on the web such as this. (Sometimes I think they get paid by the word!)

Add this to your functions.php file

function manyposts($atts) {
$postsperpage = get_option('posts_per_page');
return $postsperpage;
}
add_shortcode('showhowmany', 'manyposts');

And this in any page or post with the square brackets.
[showhowmany]

DONE!

Explanation: –
There is a function called howmanyposts ($atts is not used just a default variable. Leave it!)
$postsperpage variable finds how many pages wordpress has and saves as a number.
Then it returns it when called.
The ‘addshortcode’ part says when you type [showhowmany], wordpress will run the function called manyposts.

Then all you need to do is type [showhowmany] and it will replace the shortcode with whatever result comes back from the function.

Was that so hard, after 30 other tutorials trying to explain it in depth…WHY….

Here’s a handy utility for generating shortcodes

To move a shortcode around with CSS: –

If you add this code to the bottom of your functions file

function manyposts($atts) {
$postsperpage = get_option('posts_per_page');
return $postsperpage;
}
add_shortcode('showhowmany', 'manyposts');

Call it by using [showhowmany] in a wordpress page, it will show a number. to add CSS to this you will need to change the functions file. (as below)

function manyposts($atts) {
$postsperpage = get_option('posts_per_page');
$withcss = "

$postsperpage

";
return $withcss;
}
add_shortcode('showhowmany', 'manyposts');

You can add a class name instead of inline styling.

To make sure it appears where you want it to and not at the top, dont use echo (use return instead)
function makepod($atts) {

$cat = "

Latest Snippets

";
$args = array( 'numberposts' => '6' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$cat.= '

';
}
$cat .= "

";
return $cat;
}

add_shortcode('showpod', 'makepod');

With added javascript

function manyposts($atts) {

?>

With added Jquery! (thank me later!)

Notice the dollar has been replaced with jQuery

function manyposts($atts) {
?>