Support » Fixing WordPress » Replacing Code in Parsing Posts

  • Resolved Sean

    (@aristophanes)


    I’m not sure if I’m phrasing my question correctly, but I would like to know how I could use php to replace certain code in a post with something else. For example, if I make a post with tags in it (say, <x>), will I be able to write something in the post loop which will replace <x> with <y> or even eliminate it altogether?

    My specific case is with the WP Print plugin. There are tags in my posts which I want to appear when the visitor is viewing it onscreen, but which I don’t want to print. So when the plugin parses (is that the right word?) the post information, I would like to write in an exclusion rule to take out the tags and their contents. If I’m not mistaken, this rules out the use of str_replace.

    The plugin seems to use a standard post loop.

    Thanks for taking the time to read this.

    (Also, is there a way to preserve tabs and spaces inside the backticks when posting here?)

Viewing 6 replies - 1 through 6 (of 6 total)
  • Yes, you can do this, using the “the_content” filter hook. (See here for more on the filter hooks, and here for an example of using “the_content” to replace something).

    Sean

    (@aristophanes)

    Thanks very much filosofo.

    Sean

    (@aristophanes)

    I’ve had a chance to study the links you gave me closer – thanks, they were very helpful. However I don’t see a php function I could use that will replace not just the tags, but their contents as well. Doesn’t preg_replace just replace one thing for another?

    However I don’t see a php function I could use that will replace not just the tags, but their contents as well. Doesn’t preg_replace just replace one thing for another?

    I’m not really sure what you mean: filtering “the_content” will allow to replace anything appearing within your post, tags and all.

    preg_replace uses regular expressions, so you can have it search and replace patterns, not just strings. In other words, you can set it up to replace everything between tags <x> and </x>, including the tags themselves, if you want.

    Sean

    (@aristophanes)

    Oh, ok – thanks:) I must have misread the php website.

    Sean

    (@aristophanes)

    For those new to PHP like me, this code will remove embedded tags and their contents. You can stick it in wherever you want the php to apply (in my case, within another plugin).

    function remove_embedded ($content) {
    return preg_replace('/<tag>(.*)</tag>/',"",$content);
    }
    add_filter('the_content','remove_embedded');

    To understand the code you will want to read the notes appended to this page.

    Thanks again filosofo.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Replacing Code in Parsing Posts’ is closed to new replies.