Still learning wordpress and trying to navigate my way around adding a different shortcode to pages that use the same custom template.
Using this shortcode example I can place it in the template file in the spot I need it:
<?php echo do_shortcode('[shortcode]');?>
The issue is I need to produce multiple pages each with its own unique shortcode. My "obstacles" are;
- cannot use shortcode in text editor because it does not recognise template content
- cannot add using Elementor because the template area is fixed
- how can I specify what part of the page to show the shortcode
I believe there a is way using do_shortcode with a filter hook in the functions.php file of the child theme something like this;
<?php if ( have_posts() ):
while ( have_posts() ): the_post();
if ( get_the_content() !== '' ):
echo do_shortcode( get_the_content() );
endif;
endwhile;
endif; ?>
I am a beginner and not sure which way to do it and hoping to learn from the experts here.
2
Answers
You’re on the right track! To use different shortcodes on multiple pages that share the same custom template, you can indeed utilize the ‘do_shortcode‘ function along with custom fields or post meta data. Here’s a basic example of how you can achieve this:
In your WordPress admin, create a custom field (e.g., shortcode) for each page where you want to use a different shortcode.
In your custom template file, use ‘get_post_meta‘ to retrieve the shortcode from the custom field:
This code will fetch the shortcode specific to each page from the custom field and execute it using ‘do_shortcode‘. Now, you can assign a unique shortcode to each page using the custom field, giving you the flexibility to use different shortcodes on pages with the same template.
You can get the current post, post_id inside the shortcode, then proceed based on it’s custom meta, etc..
Inside the shortcode function.