【问题标题】:Wordpress Gallery Shortcode PregreplaceWordpress Gallery 简码 Pregreplace
【发布时间】:2013-08-15 14:57:50
【问题描述】:

基本上我需要从 Wordpress 内容中删除图库短代码,我正在使用

echo preg_replace('/\[gallery ids=[^\]]+\]/', '',  get_the_content() );

它成功删除了图库短代码,还有我需要保留的段落标签。我的想法是我想输出内容中除图库之外的所有内容。

【问题讨论】:

    标签: wordpress gallery shortcode


    【解决方案1】:

    你可以使用Wordpress strip_shortcode function

    查看 Codex 中的示例。 您可以创建一个去除短代码的过滤器:

    function remove_shortcode_from($content) {
      $content = strip_shortcodes( $content );
      return $content;
    }
    

    并在需要时调用它(在您的模板中):

    add_filter('the_content', 'remove_shortcode_from');
    the_content();
    remove_filter('the_content', 'remove_shortcode_from')
    

    编辑 1

    另一种获取方式(并回答您的评论)您可以在删除不受欢迎的短代码后在内容中使用Wordpress apply_filters function

    //within loop
    $content = get_the_content();
    $content = preg_replace('/\[gallery ids=[^\]]+\]/', '',  $content );
    $content = apply_filters('the_content', $content );
    echo $content;
    

    但我不建议你这样做。我认为强迫您的网站修改帖子的内容可能会让人难以理解。也许您应该使用Wordpress Excerpt 并避免任何问题。

    A link that helped me

    【讨论】:

    • 这是一个很好的解决方案,并且非常适合我想要实现的目标,但是对于更复杂的主题,剥离所有短代码可能会变得很麻烦。
    【解决方案2】:

    要删除短代码或特定的短代码列表,您可以使用此代码。

    global $remove_shortcode;
    /**
    * Strips and Removes shortcode if exists
    * @global int $remove_shortcode
    * @param type $shortcodes comma seprated string, array of shortcodes
    * @return content || excerpt
    */
    function dot1_strip_shortcode( $shortcodes ){
      global $remove_shortcode;
      if(empty($shortcodes)) return;
    
      if(!is_array($shortcodes)){
        $shortcodes = explode(',', $shortcodes);
      }
      foreach( $shortcodes as $shortcode ){
        $shortcode = trim($shortcode);
        if( shortcode_exists($shortcode) ){
            remove_shortcode($shortcode);
        }
        $remove_shortcode[$shortcode] = 1;
      }
      add_filter( 'the_excerpt', 'strip_shortcode' );
      add_filter( 'the_content', 'strip_shortcode' );    
    }
    function strip_shortcode( $content) {
      global $shortcode_tags, $remove_shortcode;
    
      $stack = $shortcode_tags;
      $shortcode_tags = $remove_shortcode;
      $content = strip_shortcodes($content);
    
      $shortcode_tags = $stack;
      return $content;
    }
    dot1_strip_shortcode( 'gallery' );
    

    接受单个逗号分隔的简码字符串或简码数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 2017-08-21
      相关资源
      最近更新 更多