Wordpress, PHP, url encoding error

Wordpress provides a function called "the_permalink ()" that returns, you guessed it, a permalink to a given post in a post loop.

I am trying to recode the url to this link and when I execute this code:

<?php
print(the_permalink());
$permalink = the_permalink();
print($permalink);
print(urlencode(the_permalink()));
print(urlencode($permalink));
$url = 'http://wpmu.local/graphjam/2008/11/06/test4/';
print($url);
print(urlencode($url));
?>

      

it produces these results in HTML:

http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http://wpmu.local/graphjam/2008/11/06/test4/
http%3A%2F%2Fwpmu.local%2Fgraphjam%2F2008%2F11%2F06%2Ftest4%2F

      

I would expect lines 2, 3 and 5 of the output code to be URL encoded, but only line 5 is that. Thoughts?

+1


source to share


3 answers


According to the docs, the_permalink

prints the permalink and returns it. So it urlencode

gets nothing to encode.

Try it get_permalink

.


[ CHANGE ]



A bit late for editing, but I didn't realize the number of prints was such an issue.

Here's where they all are:

<?php
print(the_permalink());                                // prints (1)
$permalink = the_permalink();                          // prints (2)
print($permalink);                                     // nothing
print(urlencode(the_permalink()));                     // prints (3)
print(urlencode($permalink));                          // nothing
$url = 'http://wpmu.local/graphjam/2008/11/06/test4/'; 
print($url);                                           // prints (4)
print(urlencode($url));                                // prints (5)
?>

      

+11


source


the_permalink()

echo permalink

get_the_permalink()

returns a permalink, so it can be assigned to a variable.



(the same happens with most functions in WordPress: the_something () has get_the_something () to return a value instead of an echo)

+7


source


@ Jonathan has a reason why you should be dealing with this in WordPress (i.e. using the correct function for the job).

Here's how to fix it when there is no function that returns a string:

ob_start();
the_permalink();
$permalink = ob_get_clean();
print(urlencode($permalink));

      

+5


source







All Articles