0

我的主题功能页面中有以下功能。基本上它所做的是在帖子页面中查找任何图像并添加一些带有 css 的跨度以动态创建一个 pinterest 按钮。

function insert_pinterest($content) {
global $post;

$posturl = urlencode(get_permalink()); //Get the post URL
$pinspan = '<span class="pinterest-button">';
$pinurlNew = '<a href="#" onclick="window.open(&quot;http://pinterest.com/pin/create/button/?url='.$posturl.'&amp;media=';

$pindescription = '&amp;description='.urlencode(get_the_title());
$options = '&quot;,&quot;Pinterest&quot;,&quot;scrollbars=no,menubar=no,width=600,height=380,resizable=yes,toolbar=no,location=no,status=no';
$pinfinish = '&quot;);return false;" class="pin-it"></a>';
$pinend = '</span>';
$pattern = '/<img(.*?)src="(.*?).(bmp|gif|jpeg|jpg|png)"(.*?) \/>/i';
$replacement = $pinspan.$pinurlNew.'$2.$3'.$pindescription.$options.$pinfinish.'<img$1src="$2.$3" $4 />'.$pinend;
$content = preg_replace( $pattern, $replacement, $content );

//Fix the link problem
$newpattern = '/<a(.*?)><span class="pinterest-button"><a(.*?)><\/a><img(.*?)\/><\/span><\/a>/i';
$replacement = '<span class="pinterest-button"><a$2></a><a$1><img$3\/></a></span>';

$content = preg_replace( $newpattern, $replacement, $content );
return $content;
}
add_filter( 'the_content', 'insert_pinterest' );

它做的一切都很好。但是有没有办法让它跳过一个带有特定类名的图像,比如“noPin”?

4

2 回答 2

1

我会使用 preg_replace_callback 来检查匹配的图像是否包含 noPin。

function skipNoPin($matches){
    if ( strpos($matches[0], "noPin") === false){
        return $pinspan.$pinurlNew.'$matches[2].$matches[3]'.$pindescription.$options.$pinfinish.'<img$1src="$2.$3" $4 />'.$pinend;
    } else {
        return $matches[0]

$content = preg_replace_callback( 
    $pattern, 
    skipNoPin,
    $content );

可以想象,另一个图像属性可能包含 noPin,如果您担心这种边缘情况,只需使 if 语句中的测试更具体。

于 2012-11-28T22:21:43.870 回答
0

You have to exclude the class noPin from the $pattern regexp :

$pattern = '/<img(.*?)src="(.*?).(bmp|gif|jpeg|jpg|png)"(.*?) \/>/i';

Has to become something like

$pattern = '/<img(.*?)src="(.*?).(bmp|gif|jpeg|jpg|png)"(.*?) (?!class="noPin") \/>/i';

Please check the regexp syntax, but the idea is to exclude class="noPin" from the searched pattern. Then your replacement will not be added to these images.

于 2012-11-28T22:04:06.507 回答