wordpress - Handling URLs correctly with PHP
i have the following case within my plugin for wordpress: I have a details page of a database entry which can be accessed like this:
http://localhost:8888/studio/wp-admin/admin.php?page=myplugin-details&id=42
The next would be to add sorting options to this page and i solved it with this code:
The url would be:
http://localhost:8888/studio/wp-admin/admin.php?page=myplugin-details&id=42&orderby=answer&order=asc
<?php
if (!empty($_GET['orderby'])) {
$pos = strpos($_SERVER["REQUEST_URI"], 'orderby');
$url = substr($_SERVER["REQUEST_URI"], 0, $pos-1);
if ($_GET['order'] == 'desc') {
echo '<th >';
echo '<a href="'.$url.'&orderby=answer&order=asc">';
} else {
echo '<th >';
echo '<a href="'.$url.'&orderby=answer&order=desc">';
}
} else {
echo '<th >';
echo '<a href="'.$_SERVER["REQUEST_URI"].'&orderby=answer&order=asc">';
}
?>
This works fine, but do i have to do that URL/REQUEST_URI stuff or is there a solution which is much simpler?
Thanks!
Answer
Solution:
In my opinion you should not use
to extract the URL. Things could get funky if you made changes to your code later on. You could use
instead :