1

I have a custom post type bhour, with a field bh_shortcode. When a post of this type is saved, I'd like it to add a shortcode based on the post's value of bh_shortcode.

If the value of bh_shortcode is "test", and when a [test] shortcode tag appears on a normal post type, nothing happens--[test] text is not replaced.

If I place add_shortcode('test','save_bhour_details'); outside of the function, the [test] text is replaced.

How can I use the add_shortcode function inside of another function?

function bhour_shortcode_handler(){
    global $post,$bhourdays;

    $output='<p>this is a test</p>';

    return $output; 
}



add_action('save_post', 'save_bhour_details');

function save_bhour_details(){
    global $post, $bhourdays;

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
        return;
    }

    if ( get_post_type($post) != 'bhours'){
        return;
    }

    //retrieve current values
    $current = get_post_custom();

    //if($_POST['bh_shortcode']!==$current['bh_shortcode'][0]){
        //remove current shortcode
        remove_shortcode($current['bh_shortcode'][0]);  

        //save new value
        save_bhour_field('bh_shortcode');

        //get current values
        $current = get_post_custom();

        //register new shortcode
        add_shortcode($current['bh_shortcode'][0], 'bhour_shortcode_handler');
    //}

    //register new shortcode
    add_shortcode($current['bh_shortcode'][0], 'bhour_shortcode_handler');
}
1

Just use as per the following code sample in your plugin.,

function wp_shortcode( $atts ) {
    extract( shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
    ), $atts ) );


    //return "foo = {$foo}";
    return your_function();
}
add_shortcode( 'your-shortcode', 'wp_shortcode' );

I think this may help for you to get your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.