WordPress.org

Ready to get started?Download WordPress

Forums

removing carriage return (\n) from the_excerpt_rss() (6 posts)

  1. chafikb
    Member
    Posted 6 years ago #

    Greetings, I'm new to wordpress and PHP. I'm trying to retrive the the_excerpt_rss() and assign it to a javascript varaible. something similar to this.
    var myDesc = '<?php the_excerpt_rss(); ?>';
    the problem is that the output of the_excerpt_rss() has a carriage return in it (\n) which outputs this to the browser

    var myDesc = 'my value
    breks js';

    which obviously breaks the JS code. How do I get around this issue? I tried wrapping it with str_replace() to get rid of the \n, but that didn't work. any help is appreciated.

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    Dunno why. str_replace() should work fine. If using \r and \n don't work, you could use the chr() function.

    However, the_excerpt_rss() actually outputs the excerpt. You need to get it back as a string. Which means calling get_the_excerpt and applying the_excerpt_rss filter yourself, manually.

    var myDesc ='<?php echo str_replace(
    array(chr(13), chr(10)),
    array('',''),
    apply_filters('the_excerpt_rss',
    get_the_excerpt()) ); ?>';
  3. chafikb
    Member
    Posted 6 years ago #

    Otto42, this seems to have done the job :) can you explain to me what this code is doing other than replacing the 13 and 10 chars? is it doing the exacatly the same thing as what I was trying to do previously? Thanks.

  4. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    Breakdown:

    1. It calls get_the_excerpt to.. well.. get the excerpt. :)
    2. It applies the_excerpt_rss filters to that, if any.
    3. It replaces \r's and \n's with nothing, thus removing them.
    4. Finally, it echos the result of all this, putting it into the html.

  5. chafikb
    Member
    Posted 6 years ago #

    Otto42, Thanks for the breakdown. I noticed that this code is echoing [...] at the end. is there a way to avoid doing that? Thanks.

  6. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    The [...] is part of the excerpt itself. WordPress intentionally adds that when there's more content. You could remove it with the str_replace in the same way, but why would you want to? It shows that there's more content there.

    If you want all the content, use the_content instead of the_excerpt.

Topic Closed

This topic has been closed to new replies.

About this Topic