Create Short Code with Multiple attributes

We are going to add short code and create some of its attribute

We want to call post data on different pages with different categories and number of posts to show
also we can set post type

add this code in function.php


// This is a function for shortcode 
function custom_shortcode() {
     return 'hi i am short code function';
}

add_shortcode( 'shortcode', 'custom_shortcode' );

call this by using [shortcode]

Now lets add some code in this function


function custom_shortcode($atts) {
	$atts = shortcode_atts(
		array(
			'post' => 'posts',               //Default Value
			'category' => 'uncategorized',   //Default Value
			'show' => '5',                   //Default Value
		),
		$atts
	);

	$args=array( 
		'post_type' => $atts['post'],
		'category_name'  => $atts['category'],
		'posts_per_page' => $atts['show']
	);
	
	$my_query = null;
	$my_query = new WP_Query($args);
	
	while ($my_query->have_posts()) : $my_query->the_post(); ?>
		<div class="container text-center">
			<h2><?php the_title(); ?></h2>
			<div>
				<?php the_content(); ?>
			</div>
		</div>
	<?php 
	endwhile; 
	wp_reset_query(); 

}
add_shortcode( 'getposts', 'custom_shortcode' );

After adding this code in function.php

go and create new page and call this shortcode function by using

[getposts] // This will show your default top 5 posts

[getposts post=”post type name” category=”Category name here” show=”post you want to show”]
[getposts post=”faqs” category=”category_questions” show=”5″]

if you want to call this short code in php file so you can use

do_shortcode();

ex:
do_shortcode(‘[getposts]’);
do_shortcode(‘[getposts post=”faqs” category=”category_questions” show=”5″]’);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s