Automatic linking: Ignore preg_replace in headlines and links
-
Hello,
I try to code my own WordPress glossary.
So I’ve created the post type ‘glossary’ and now I am busy with automatic linking. I want the title of an glossary post to be link if it is part of content (post_content) of any post (only the first time it is mentioned).
I use
preg_replace()
to replace the title with the link. The following code is working fine. But I have one big problem: I don’t want to get replacements in headlines <h1>-<h6> and in links .I don’t know how to get this working. I think I need some PHP regex stuff, or another function, or I don’t now – my head is spinning…
Does someone has an idea how to say something like “replace everywhere but not in headlines and links!”?
There’s my function:
function glossary_links($content) { global $post; $glossary_index = get_posts(array('post_type' => 'glossary', 'post_status' => 'publish', 'numberposts' => -1)); foreach ($glossary_index as $glossary_item) { if(strstr($content, $glossary_item->post_title)) { $search = '/' . $glossary_item->post_title . '/'; $replace = '<a class="glossar-link" href="' . get_home_url() . '/glossar/' . $glossary_item->post_name . '">' . $glossary_item->post_title . '</a>'; $content = preg_replace($search, $replace, $content, 1); } } return $content; } add_filter('the_content', 'glossary_links');
For my tests, I’ve created some general regex for this. I don’t know if this helpes (it doesn’t work correctly but it’s an approach).
if(preg_match_all('/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/iu', $content)) echo "Link"; if(preg_match_all('/<h[1-6]['.$glossary_item->post_title.']*>.*?<\/h[1-6]>/si', $content)) echo "Headline";
Thanks for any help you can offer.
saNNNy
- The topic ‘Automatic linking: Ignore preg_replace in headlines and links’ is closed to new replies.