An example of how to create a WordPress shortcode to display a custom template with custom attributes to pass on the template.

Code is added in the functions.php file
This example displays all the CPT testimonials with a custom Heading

The shortcode to use is [ display_testimonials ]

with a custom attribute use [ display_testimonials heading=”Custom Text”]

function template_part_shortcode($atts) {
        $atts = shortcode_atts(
        array(
            'heading' => '',
        ), $atts, 'display_testimonials' );
    ob_start();
    get_template_part( 'partials/testimonials', null , array('data'  => array('heading' => $atts['heading'])));
    return ob_get_clean();
}
add_shortcode( 'display_testimonials', 'template_part_shortcode' );

On the testimonials.php file the codes is added

<?php $args = wp_parse_args( $args, $array_defaults ); 
	$blog_posts_query = new WP_Query([
    'post_type' => 'testimonials',
    'posts_per_page' => -1,
    'orderby' => 'date',
	'order' => 'ASC'
]);
?>
<!-- The Modal -->
<div id="testimonials_section">
	<div class="container">
	    <?php if(!empty($args['data']['heading'])): ?>
	        <div class="row">
				<div class="col-12">
		    		<h3 class="bp-title"><strong><?php echo esc_html($args['data']['heading']); ?></strong></h3>
				</div>
			</div>
	    <?php endif; ?>		
        <?php if ($blog_posts_query->have_posts()): ?>
			<div class="row">
	            <?php while ($blog_posts_query->have_posts()): ?>
	                <?php $blog_posts_query->the_post(); ?>
	                <div class="col-4">
						<!--<h3><?php echo get_the_title() ?></h3>-->
						<?php the_content(); ?>
					</div>						
	            <?php endwhile; ?>
            </div>
        <?php endif; ?>		
				
	</div>
</div>
<?php wp_reset_query(); ?>
Share this:

Contact me.

I would love to hear from you, send me a message using the form below.

    ×