Wordpress从帖子中删除单个短代码


Wordpress strip single shortcode from posts

我只想去掉我博客文章中的[gallery]短代码。我找到的唯一解决方案是添加到函数中的过滤器。

function remove_gallery($content) {
  if ( is_single() ) {
    $content = strip_shortcodes( $content );
  }
  return $content;
}
add_filter('the_content', 'remove_gallery');

它删除了所有的短代码,包括[caption],我需要的图像。如何指定要排除或包含的单个快捷代码?

要只删除库快捷代码,请注册一个返回空字符串的回调函数:

add_shortcode('gallery', '__return_false');

但这只适用于回调。要静态执行,您可以临时更改wordpress的全局状态以欺骗它:

/**
 * @param string $code name of the shortcode
 * @param string $content
 * @return string content with shortcode striped
 */
function strip_shortcode($code, $content)
{
    global $shortcode_tags;
    $stack = $shortcode_tags;
    $shortcode_tags = array($code => 1);
    $content = strip_shortcodes($content);
    $shortcode_tags = $stack;
    return $content;
}

用法:

$content = strip_shortcode('gallery', $content);

对我来说,使用过:

add_shortcode('shortcode_name', '__return_false');

如果我尝试strip_shortcode,它们将删除所有shortocode并更改最终结果

如果您只想获取内容,不想获取任何短代码,请尝试类似的方法

global $post;
$postContentStr = apply_filters('the_content', strip_shortcodes($post->post_content));
echo $postContentStr;