Update Shortcode Element to pass post ID
-
I have a custom post type with some custom postmeta fields as part of it. I was looking for a way to add that custom postmeta content to part of a post without having to recreate the entire layout using “ymc/post/layout/custom_{filter_id}”.
I poked around and put a shortcode element into my custom layout and that almost got me there, as it allowed me to put custom content in but not to differentiate the content based on the post.
Poking around some more, I found the renderShortode function in the FG_Layout_Renderer.php file and I made two simple changes to it.
- I set $post_id from $field
- I rewrote the shortcode text that was passed in to insert an attribute ‘post_id=$post_id’
This worked great. Now, in my custom shortcode handler I can call get_post_meta() using the post_id. That is great for me, but of course the next time the plugin is updated it will get overwritten.
I was hoping you could add this to the actual codebase. It is a pretty simple change and makes the Shortcode element much more powerful. It will even work with shortcodes that already pass attributes since you just put spaces between attributes in a call to a shortcode and this just adds it to the end.
Thanks for the consideration.
protected static function renderShortcode(array $field, array $settings) : void {
$shortcode_text = $settings['content'] ?? '';
$class = self::getCustomClass($settings);
$post_id = $field['post']->ID; //NEW
if (!empty($shortcode_text)) {
$shortcode_text = str_replace(']', ' post_id="' . $post_id . '" ]', $shortcode_text); //NEW
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo sprintf(
'<div class="post-card__shortcode sb-shortcode %s">%s</div>',
esc_attr($class),
do_shortcode($shortcode_text)
);
}
}
You must be logged in to reply to this topic.