Issue
I want to create short code every time when post is published using that specific post content so that i have short codes for each different post, for this i wrote this code, but its not working, can anyone please help.
add_action('publish_adsmanager_banner','create_banner_shortcode');
function create_banner_shortcode()
{
add_shortcode( 'banner_'.get_the_ID().'', 'custom_shortcode' );
}
function custom_shortcode($post_id) {
$message = get_the_content($post_id);
return $message;
}
Solution
What if you will just pass an id as an attribute to this shortcode?
add_shortcode( 'my_banner', 'custom_shortcode' ); // [my_banner id="123"]
function custom_shortcode( $atts ) {
$atts = shortcode_atts(
array(
'id' => null,
),
$atts
);
$message = get_the_content( $atts['id'] );
return $message;
}
In your original idea, you cannot create an id-named shortcode just once, it should be registered on each wp init. But in this case, it is hard to get a post context just from the shortcode name, you have to pass an id on each shortcode registration. The solution above will allow you to keep DRY especially if you know the ID of each banner when using them.
Answered By - Ivan Karpushchenko
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.