【问题标题】:Excluding tag Link from html tags in Post content从帖子内容中的html标签中排除标签链接
【发布时间】:2018-06-27 21:30:32
【问题描述】:

请我想实现从下面的代码中排除<h2>, <a> and <img> html 标记的目标。我正在尝试用帖子内容中的链接替换标签关键字,并排除标签链接影响我上面列出的html标签。

function link_words( $text ) {
                $tags = get_tags();
                if ( $tags ) {
                    foreach ( $tags as $tag ) {
                        $from = '/' . $tag->name . '/';
                        $to = sprintf( '<a href="%s">%s</a>', esc_url( get_term_link( $tag ) ), esc_html( $tag->name ) );
                        $text = preg_replace($from, $to , $text, 2);
                    }
                }
                return $text;
            }
            add_filter( 'the_content', 'link_words' );

请在房子里的大师,有什么出路吗?我是 wp 函数编码的新手。

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    对于简单的 HTML,你可以做一个 str_replace:

    $text = str_replace(array("<h2>","</h2>"), "", $text);
    

    去除那些更复杂的标签:

    $text = preg_replace("/<img[^>]+\>/i", "", $text);
    $text = preg_replace("/<a\s[^>]+\>/i", "", $text);
    

    我刚刚测试了下面的代码,它似乎可以工作:

    function link_words( $text ) {
    
        $text = str_replace(array("<h2>","</h2>","</a>"), "", $text);
        $text = preg_replace("/<img[^>]+\>/i", "", $text);
        $text = preg_replace("/<a\s[^>]+\>/i", "", $text);
        return $text;
    
    }
    add_filter( 'the_content', 'link_words' );
    

    【讨论】:

    • 你能帮我在 OP 代码上实现它吗?我是 wp 编码的新手。
    • 我已经为您测试并重写了该功能 - 现在应该可以使用了。如果有帮助,请投票并接受我的回答:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2011-10-31
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多