I'm trying to remove trailing slash from a link which I get from previous_posts_link() function. Here is my code:

<?php rtrim(previous_posts_link( __( 'text', 'name' ) ), '/'); ?>

Unfortunetly it doesn't work and I still get the slash at the end of url.


There's two problems here:

  1. previous_posts_link() echoes the link, rather than returning it.
  2. previous_posts_link() returns the full HTML of the link, including <a href=""> etc.

The problem with #1 is that for you to be able pass the result of a function to another function (such as rtrim()) as an argument, that function needs to return a value, not print it to the screen using echo or similar. The function that returns the value of previous_posts_link() is get_previous_posts_link().

However, this still won't solve your problem, because of #2. get_previous_posts_link() will return a value like this:

'<a href="https://example.com/2019/02/08/previous-post/">« Previous Post</a>'

As you can see, this does not end with a slash. The slash is in the middle of the string as part of the URL.

If you only want the URL, you need to use get_previous_posts_page_link(). Then you can remove the trailing slash:

<?php echo rtrim( get_previous_posts_page_link(), '/' ); ?>

Now, just to cover all my bases; if you want to get the full HTML link and remove the trailing slash from inside it, then you're going to need a couple more steps.

Firstly, you're going to need to use get_previous_posts_link(), which is the function that returns the full HTML, rather than echoing it. Then you're going to need to extract the URL from the HTML, remove the trailing slash, then put it back. That will look something like this:

// Get the HTML for the link.
$previous_posts_link = get_previous_posts_link( __( 'text', 'name' ) );

// Find the URL.
preg_match( '/href="([^"]*)"/', $previous_posts_link, $matches );

// Remove the trailing slash from the original URL.
$original_url = $matches[1];
$trimmed_url  = untrailingslashit( $original_url );

// Replace the original URL with the version without a slash.
$previous_posts_link = str_replace( $original_url, $trimmed_url, $previous_posts_link );

// Output it
echo $previous_posts_link;

I have no idea why you'd want or need to do that though.

PS: untrailingslashit() is a WordPress helper function that removes trailing forward and back slashes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.