Step-by-Step Guide: Using Shortcodes to Pass Values to WordPress Template Parts

Pass Values to WordPress Template Parts

Step 1: Create the Shortcode

First, you need to create a shortcode that will be used to pass values to the template part. Add the following code to your theme’s functions.php file:

php
function my_custom_shortcode($atts) {
// Set up default attributes and merge with the passed attributes
$atts = shortcode_atts(
array(
'title' => 'Default Title',
'content' => 'Default Content',
),
$atts,
'my_shortcode'
);// Capture the template part output
ob_start();
get_template_part('template-parts/my-template', null, $atts);
return ob_get_clean();
}
add_shortcode('my_shortcode', 'my_custom_shortcode');

Step 2: Create the Template Part

Next, create the template part file in your theme. For example, create a file named my-template.php inside a folder named template-parts in your theme directory. In template-parts/my-template.php, you can access the passed values using the $args array:

php
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
// Access the passed values $title = $args['title']; $content = $args['content']; ?>
<div class="my-template-part">
<h2><?php echo esc_html($title); ?></h2>
<p><?php echo esc_html($content); ?></p>
</div>

Step 3: Use the Shortcode

You can now use the shortcode in any post or page to pass values to the template part:

html
[my_shortcode title="Custom Title" content="Custom Content"]

This will render the template part with the values you passed via the shortcode attributes.

Summary

  1. Create the Shortcode: Define the shortcode in your theme’s functions.php file, setting up default attributes and capturing the template part output.
  2. Create the Template Part:In the template part file, access the passed values using the $args array.
  3. Use the Shortcode: Insert the shortcode in a post or page, passing custom values as attributes.

By following these steps, you can easily pass values to a template part included in a shortcode in WordPress.