I’m having trouble with URL encoding in WordPress. I need to encode permalinks but something weird is happening.
There’s this WordPress function called the_permalink() that gives you the URL for a post when you’re looping through posts. When I try to encode it with PHP’s urlencode() function, it doesn’t work as expected.
Here’s what I’m testing:
<?php
echo get_permalink();
$post_url = get_permalink();
echo $post_url;
echo urlencode(get_permalink());
echo urlencode($post_url);
$sample_url = 'http://mysite.local/blog/2023/12/15/sample-post/';
echo $sample_url;
echo urlencode($sample_url);
?>
The output I get is:
http://mysite.local/blog/2023/12/15/sample-post/
http://mysite.local/blog/2023/12/15/sample-post/
http://mysite.local/blog/2023/12/15/sample-post/
http://mysite.local/blog/2023/12/15/sample-post/
http%3A%2F%2Fmysite.local%2Fblog%2F2023%2F12%2F15%2Fsample-post%2F
Only the last line shows proper URL encoding. The other attempts with the permalink function don’t get encoded at all. What am I missing here?