问题
I'm trying to create a Shortcode to use as a wrapper so as to deflect the wpautop() function from coming into effect.
Yes, I know how to remove the auto formatting in it's entirety but the goal is to create a custom Shortcode that I can wrap around an < img tag and circumvent the auto format in select cases.
I've created this Shortcode :
function no_wp_autoformat_shortcode() {
return null;
}
add_shortcode('nowpautop', 'no_wp_autoformat_shortcode');
But when applied the image simply disappears.
How can I create a Shortcode that has a null effect (does nothing to the wrapped element)?
[nowpautop] img tag here [/nowpautop]
This question is an extension of this one: Create shortcode in Wordpress that disables wpautop() on wrapped content? as I believe this question is more to the point.
回答1:
add_action( 'init', function() {
add_filter( 'the_content', function( $content ) use ( &$matches ) {
# save content between nowpautop tags, priority 9 means that this will run before wpautop
preg_match_all( '#\[nowpautop\](.*?)\[/nowpautop\]#', $content, $matches, PREG_PATTERN_ORDER );
# this filter returns $content unchanged and is run only to save the original content between nowpautop tags
return $content;
}, 9 );
add_shortcode( 'nowpautop', function( $atts, $content ) use ( &$matches ) {
# restore the original content between nowpautop tags
static $index = 0;
return $matches[1][$index++];
});
});
回答2:
SOLVED
Shortcodes REPLACE content so the solution uses attributes to shift the wrapped element to become the source and the Shortcode wrapper to set the start and close of the
Here is a working example if anyone has a similar case they are looking to solve. Note function and shortcode name should be changed to something more appropriate.
Create Shortcode in functions.php (Child)
function no_wp_autoformat_shortcode( $atts, $content = null ) {
return '<img style="max-width: 50px; width: 100%;" src="'. $content .'" alt="SGD Advantage" />';
}
add_shortcode('nowpautop', 'no_wp_autoformat_shortcode');
In use on page:
<h3 style="display:inline;">Graphic Advantage</h3>
[nowpautop]https://sgdesign.com/images/SGDadvantage.png[/nowpautop]
Final Result: < h3 style="display:inline;">Graphic Advantage< /h3> < img style="max-width: 50px; width: 100%;" src="https://sgdesign.com/images/SGDadvantage.png" alt="SGD Advantage" />
Because the < h3 is styled as "inline" the graphic now follows on the same line achieving the primary goal.
来源:https://stackoverflow.com/questions/46597308/how-to-create-a-wordpress-shortcode-that-does-nothing