PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 6, 2022

[FIXED] how to create shortcode using post content for each post when the post is published

 February 06, 2022     plugins, shortcode, wordpress     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing