【问题标题】:How to add HTML Tag and class inside Link Tag in Post - Wordpress如何在 Post 的链接标签中添加 HTML 标签和类 - Wordpress
【发布时间】:2019-05-25 00:36:19
【问题描述】:

我想在 Post 的链接标签内添加类和 html 标签,所以我将一个单词链接到我的一个 wordpress 页面,如下所示:

<a href="http://localhost/website/contact/">contact</a>

当我链接它时,我希望它是这样的:

<a href="http://localhost/website/contact/" class="class1 class2"><span>contact</span></a>

因为我的主题使用span 来实现悬停功能。

如果可能仅在帖子(博客部分)中,有一个所有帖子都有的类:post-contents

我知道我可以在我的帖子的 HTML 代码中进行修改,但我希望它是通用的,所以只要我在帖子中添加链接(甚至是新链接),就会添加 class 和 span 标签

有什么想法吗?

【问题讨论】:

    标签: html css wordpress


    【解决方案1】:

    这应该可以解决问题;

    function wrap_anchor_text_with_span( $content ) {
            if ( ! is_admin() && preg_match( '~<a(.*?)>(.*?)</a>~', $content ) ) {
                $content = preg_replace_callback( '~<a(.*?)>(.*?)</a>~', '_add_span', $content );
        }
        return $content;
    }
    add_filter('the_content', 'wrap_anchor_text_with_span', 10);
    
    function _add_span( $matches ) {
        if ( ! ( $title = strip_tags( $matches[2] ) ) ) { // If we only have an image inside the anchor
            return '<a' . $matches[1] . '>' . $matches[2] . '</a>';
        } else {
            return '<a' . $matches[1] . '><span data-title="' . esc_attr( $title ) . '">' . $matches[2] . '</span></a>';
        }
    }
    

    这个函数的作用是它连接到the_content过滤器并在所有锚标签内放置一个跨度。

    请注意,如果锚点包含图像,则不会添加跨度。根据另一个线程的另一个答案,Nikola Ivanov Nikolov

    然后使用过滤器来处理锚点...

    add_filter('the_content', 'addClassToLinks');
    function addClassToLinks($content){
        return str_replace( '<a ', "<a class='myclass'", $content);
    }
    

    希望这会有所帮助。

    问候, -B。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      • 2020-02-10
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      相关资源
      最近更新 更多