In our particular instance, we created a custom post type for Community Testimonials with a Taxonomy for Types. The Taxonomy has various terms.
We then wanted to create a shortcode that the content manager could use to display Community Testimonials based on various Types. In the end we wanted to create a shortcode that looked like [customer-testimonial type=”{THE TAXONOMY TERM}”]. This, in turn, would display all Customer Testimonials within a particular Type Term.
The output would look something like this on the frontend:
We did not want to include all the markup and query code within the functions.php in order to keep everything cleaner. Instead, we decided to create a new PHP file within the theme directory, customer-testimonials.php, to house all our markup and output. The caveat, we still wanted to pass the type parameter value to the PHP file. In the end this was pretty easy, but took us a minute to figure out, so thought we’d share.
The Code
Within functions.php or wherever you are housing the function for the shortcode, create the shortcode with the parameter:
/* Community Testimonials Shortcode */ function ctest_shortcode($atts) { extract(shortcode_atts(array( 'YOUR PARAMETER' => 'YOUR PARAMETER' ), $atts)); /* Call to template */ ob_start(); include(locate_template('YOUR-TEMPLATE.php')); return ob_get_clean(); } add_shortcode('test', 'ctest_shortcode');
Next, within your theme directory, create a new file, in our case YOUR-TEMPLATE.php. Within this file you can add any markup you want and it will be outputted when you include your shortcode. In our instance, we are creating a query of the custom post type with the taxonomy for Types and the variable is the term.
Our query:
<?php $args = array( 'post_type' => 'community_test', 'posts_per_page' => '100', 'tax_query' => array( array( 'taxonomy' => 'testimonial_type', 'field' => 'slug', 'terms' => $YOUR_PARAMETER, ) ) ); // Custom query. $query = new WP_Query( $args ); // Check that we have query results. if ( $query->have_posts() ) { // Start looping over the query results. while ( $query->have_posts() ) { $query->the_post(); ?>
Because in functions we use:
include(locate_template('YOUR-TEMPLATE.php'));
We can pass the parameter variable to our new file in our theme (YOUR-TEMPLATE.php) and then utilize it. In our case the variable is $YOUR_PARAMETER, replace this whatever the variable is you are using.
Then include the shortcode in your page, post, or wherever with the parameter and badabingbadaboom, you should be cooking.
Any questions, leave them in the comments.
Hi
1. for child theme this not working include(locate_template(‘YOUR-TEMPLATE.php’));
2. also when ‘a’ => ‘Hello’ in temp file $a not give output