WordPress: фильтрация содержимого для определенной строки в ссылках и изменение элемента на охват - PullRequest
0 голосов
/ 25 мая 2020

Я использую WordPress и хотел бы отфильтровать the_content для ссылок, содержащих конкретную строку c. Если ссылка содержит эту строку, к этому элементу следует добавить определенный класс, а элемент a следует заменить на span без каких-либо атрибутов.

Шаблон ссылки: <a href="https://example.com/specific-string/file.pdf" title="Title">Link</a>

Specifi c string: specific-string

Если ссылка содержит конкретную c строку, вывод: <span class="private">Link</span>

Итак, фильтр WordPress, который я могу использовать, выглядит следующим образом:

add_filter( 'the_content', 'the_content_filter_links', 10, 1 ); 

function the_content_filter_links( $value ) {

    // 1. Find all links that contain the string `specific-string`
    // 2. Remove all attributes from `a` tag.
    // 3. Change opening and closing `a` tags to `span`.

    // Output the content
    return $value; 
}; 

Я нашел это , чтобы получить все ссылки в PHP, но он использует класс DOMDocument, который, я думаю, не может быть использован в моем случае?

Примечание: я не хочу использовать для этого JS, потому что мне не нравится, что пользователь видит ссылку, которая может произойти, когда он / она отключил JS.

Большое спасибо за вашу помощь !

1 Ответ

1 голос
/ 25 мая 2020

Вы должны иметь возможность сделать это с помощью DOM:

<?php

print_r(the_content_filter_links('<a href="https://example.com/specific-string/file.pdf" title="Title">Link</a>'));
print_r(the_content_filter_links('<a href="https://example.com/nonspecific-string/file.pdf" title="Title">Link</a>'));

function the_content_filter_links( $value ) {

    $doc = new DOMDocument();
    $doc->loadHTML($value);
    // 1. Find all links that contain the string `specific-string`
    if (strpos($value, '/specific-string')) {
        // 2. Remove all attributes from `a` tag.    
        $link = $doc->getElementsByTagName('a')->item(0);
        // 3. Change opening and closing `a` tags to `span`.
        $value = '<span href="'.$link->getAttribute('href').'">'.$link->nodeValue.'</span>';
        // Output the content
        return $value; 
    }
    return false;
}; 

или регулярного выражения (DOM лучше):

<?php

print_r(the_content_filter_links('<a href="https://example.com/specific-string/file.pdf" title="Title">Link</a>'));
print_r(the_content_filter_links('<a href="https://example.com/nonspecific-string/file.pdf" title="Title">Link</a>'));

function the_content_filter_links( $value ) {

    // 1. Find all links that contain the string `specific-string`
    if (strpos($value, '/specific-string')) {
        // 2. Remove all attributes from `a` tag.    
        preg_match('/.*href="(.*?)".*>(.*)<\/a>/', $value, $matches);
        if(count($matches) == 3) {
            // 3. Change opening and closing `a` tags to `span`.
            // Output the content
            return '<span href="'.$matches[1].'">'.$matches[1].'</span>';
        }
    }

    return false; 
}; 
...