WordPress.org

Ready to get started?Download WordPress

Forums

how do I find and replace wordpress content characters? (5 posts)

  1. dacosta_rafael
    Member
    Posted 2 years ago #

    I have the following code but it does not seem to change the character in wordpress

    $intro_copy = get_the_content() ;

    $intro_copy = str_replace('&', '', $intro_copy);

    echo $intro_copy;

  2. dacosta_rafael
    Member
    Posted 2 years ago #

    this worked for me . let me know if there is a 'better practice'

    <?php
    function replace_content($content)
    {
    $content = str_replace("&", "&", $content);
    $content = str_replace("é", "é", $content);
    $content = str_replace("—", "—", $content);
    $content = str_replace("‘", "‘", $content);
    $content = str_replace("’", "’", $content);
    $content = str_replace('“', "“", $content);
    $content = str_replace('”', "”", $content);
    return $content;
    }

    ?>

  3. Harry
    Member
    Posted 2 years ago #

    You could add what you want to find and replace into an array, and it would probably be more efficient.

    <?php
    function replace_content($content)
    {
      $search  = array('&', 'é', '—', '‘', '’', '“', '”');
      $replace = array('&', 'é', '—', '‘', '’', '“', '”');
    
      $content = str_replace($search, $replace, $content);
      return $content;
    }
    
    ?>

    Link: http://php.net/manual/en/function.str-replace.php - Check out the array examples.

    Hope this works, I haven't actually run the above code :)

  4. rightmost
    Member
    Posted 2 years ago #

    Thanks Harry, that worked for me.

    Just to add on to this for anyone else interested... this is what I added to my functions.php file:

    <?php
    function replace_content($content)
    {
      //add content that you wish to replace to this array
      $search  = array('&', 'é', '—', '‘', '’', '“', '”');
      //add content that will replace old content to this array
      $replace = array('&', 'é', '—', '‘', '’', '“', '”');
    
      $content = str_replace($search, $replace, $content);
      return $content;
    }
    
    add_filter('the_content', 'replace_content');
    add_filter('the_excerpt', 'replace_content');
    ?>
  5. Adam
    Member
    Posted 1 year ago #

    This is great! The only issue I'm having is getting this to work for custom fields. I have many custom fields, so it's not efficient to put them all in this one function. Furthermore, as new custom fields are being created, that also leaves room for error.

    Is there a way to do a "find and replace" for an entire page? Thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic