You would want to filter the category link to add the custom variable to the category link. You can make use of the get_term_link
filter to filter the category link address
Here is a very basic idea:
Suppose that we, taken from OP, that you need to add the custom variable only to terms belonging to the build in taxonomy category
, and only when we are on a real page and we want to add the page ID as value to the URL, we can create a filter function to just do exactly that, and by using add_query_arg()
, we can add a new query variable, lets call it frompage
, to the URL.
Here is a basic function, which you can extend and modify as you see fit. I have commented the code to make it easy to follow
add_filter( 'term_link', function ( $termlink, $term, $taxonomy )
{
// If this is not a page, return the unmodified term link
if ( !is_page() ) // Change this to what is specific to your needs
return $termlink;
// Only target the build in taxonomy 'category'
if ( $taxonomy !== 'category' ) // Adjust to your exact taxonomy
return $termlink;
// Get the current viewed paged id
$current_id = get_queried_object_id();
// Make sure we actually have a value, if not, return the term link
if ( $current_id == 0 )
return $termlink;
// If we reached this point, we are good to go and should add our query var to the URL
$termlink = esc_url( add_query_arg( ['frompage' => $current_id], $termlink ) );
return $termlink;
}, 10, 3 );
You can then retrieve the value as follow:
$value = filter_input( INPUT_GET, 'frompage', FILTER_VALIDATE_INT );
if ( $value )
echo $value;
Note that I have used filter_input
here to get the $_GET
value. That is because that filter_input
validates if the passed value exists and either returns it or returns false. Also, you can pass a filter to be used on the value, in this case FILTER_VALIDATE_INT
. All in all, it is a much better and safer way than $_GET( 'frompage
)`