2016-05-31 8 views
1

投稿コンテンツのキーワードをリンクに置き換えようとしていましたが、imgタグのalt属性のキーワードも影響を受けました。 解決策はありますか?ところで、私はのfunctions.phpに使用していたコード:alt属性のキーワードに影響を与えずにWordpressでリンクするキーワードを置き換える方法

function replace_text_wp($text){ 
$replace = array( 
    'keyword1' => '<a href="http://demo.com/" rel="bookmark" title="keyword1">keyword1</a>', 
); 
$text = str_replace(array_keys($replace), $replace, $text); 
return $text; 

}

ADD_FILTER( 'the_content'、 'replace_text_wp')。

答えて

0

私が長すぎる前に類似していない何かをしなければならなかった、あなたの関数としてこれを試してみてください - 私は唯一で、おかげでサイモン

function replace_text_wp($the_content){ 
    //Break up the content into parts - allowing us to just edit content and not tags 
    $parts = preg_split('/(<(?:[^"\'>]|"[^"<]*"|\'[^\'<]*\')*>)/', $the_content, -1, PREG_SPLIT_DELIM_CAPTURE); 
    // Loop through the blocks and just edit the content 
    for ($i=0, $n=count($parts); $i<$n; $i+=2) { 
     // Check if any of our keywords are within the content 
     // If so then make the keywords a link 
     $parts[$i] = str_replace('keyword1', '<a href="http://demo.com/" rel="bookmark" title="keyword1">keyword1</a>', $parts[$i]); 
     } 
    } 
    // Now put it all back together 
    $the_content = implode('', $parts); 
    return $the_content; 
} 
+0

をテストすることなく、あなたの例にそれを適応していて、それはよく、いくつかのあいと微調整が必​​要になる場合があります正規表現のビットの変更、そしてそれは完全にうまく動作します –

+0

これは有用な、または答えてくださいアラン:)私はそれを見ることに興味があるように必要な正規表現を追加してください。 –

+0

私は使用している正規表現は、フラグや投票ができないのでまだ簡単です: 'code' $ parts = preg_split( '/(<(?: img。* | a。*)>)/' $ text、-1、PREG_SPLIT_DELIM_CAPTURE);私の場合は 'code'ですが、私はまだタグにキーワードを入れて置き換えたい –

関連する問題