How to create a shortcode/edit a function to solve

2019-03-06 15:53发布

问题:

Following on from my previously unsolved question How to show Bootstrap Buttons inline instead of one per line in Wordpress Specifically? and after extensive research in this point, I found out that that there is a conflict between Wordpress and Bootstrap.

Wordpress simplified the text editing process by introducing invisible line breaks < /br> after each line. When Using Bootstrap elements (e..g buttons) with Wordpress, a line break < /br> gets introduced after each button code, leading them to appear one button per line, likr this screenshot:

The only solution I found (which appears as an edit in my other question referred to above), is to add this function: remove_filter( 'the_content', 'wpautop' );

However, this function while it solved the Bootstrap problem, forces me to write full html on all text of all posts, otherwise the text will appear as one unformmatted block.

As a workaround for this problem, I thought of putting the Bootstrap components in a div tag, then either creating a shortcode that applies this filter to the content of of the divtag, or create a function that targets this div tag without the need to add a shortcode.

As a start, I created this shortcode function, but it didn't do anything: (yes it doesn't have a div tag specified, but I was testing if the shortcode will work, but it didn't).

    function stop_wpautop(){
    remove_filter( 'the_content', 'wpautop' );
}
    add_shortcode( 'stop-wpautop', 'stop_wpautop'); 

I also tried replacing the_content with a div tag class name that I wrapped the Bootstrap components with, but it didn't work too.

    function stop_wpautop(){
    remove_filter( 'bootstrap-components', 'wpautop' );
}
    add_shortcode( 'stop-wpautop', 'stop_wpautop'); 

Finally, I added the filter straight without a shortcode, but it didn't work too:

remove_filter( 'bootstrap-components', 'wpautop' );

So obviously, I am writing the function wrong. Can someone please guide me as to what's wrong, or any suggestion to limit the effect of the wpautop to a certain div tag only?

EDIT I can add the Bootstrap code in a custom field then show the custom field contents if this will make things easier, but I still don't know how to replace the_content with the custom field name.

Thanks in advance.

回答1:

This is the function that I am using to output the test buttons.

add_shortcode('show_boot_buttons', 'func_show_buttons');

function func_show_buttons( $atts ) {
    $atts = shortcode_atts(
        array(
            'class' => 'btn',
            'text' => 'Press Me',
        ), $atts, 'show_boot_buttons' );

    return '<button type="button" class="btn ' . esc_html( $atts['class'] ) .'">'. esc_html( $atts['text'] ). '</button>';
}

You can insert a button with the following code example.

[show_boot_buttons class="btn-primary" text="Press This"]