WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Replacing Code in Parsing Posts (7 posts)

  1. Sean
    Member
    Posted 8 years ago #

    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?)

  2. Austin Matzko
    Member
    Posted 8 years ago #

    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).

  3. Sean
    Member
    Posted 8 years ago #

    Thanks very much filosofo.

  4. Sean
    Member
    Posted 8 years ago #

    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?

  5. Austin Matzko
    Member
    Posted 8 years ago #

    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.

  6. Sean
    Member
    Posted 8 years ago #

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

  7. Sean
    Member
    Posted 8 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic