I have been trying for days and cannot get it to work
I wish to create simple filter than can add 2 parameters to every link on the entire site.
I would prefer that I can control only links have /external/ in their url is affected
I wish to add id=[id] and referrer=URL of the current page
Hope for a little help 🙂
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Assuming you mean $post->ID, you can use the post_link and post_type_link filters to append your query string. We’re using the add_query_arg() function to do this:
/**
* Modify the posts navigation WHERE clause
* to include our acceptable post types
*
* @param String $post_link - Post URL
* @param WP_Post $post - Current Post
*
* @return String
*/
function wpse375877_link_referrer( $post_link, $post ) {
// Return Early
if( is_admin() ) {
return $post_link;
}
return add_query_arg( array(
'id' => $post->ID,
'referrer' => $post_link,
) );
}
add_filter( 'post_link', 'wpse375877_link_referrer', 20, 2 );
add_filter( 'post_type_link', 'wpse375877_link_referrer', 20, 2 );
The above ensures that any WordPress functions will be given a modified post URL. Now, if we wanted to redirect any URLs missing this query string, you can use template_redirect action hook:
/**
* Redirect any items without query string
*
* @return void
*/
function wpse375877_redirect_to_referrer() {
if( ! isset( $_GET, $_GET['id'], $_GET['referrer'] ) ) {
wp_safe_redirect(
add_query_arg( array(
'id' => get_the_ID(),
'referrer' => get_permalink(),
), get_permalink() )
);
exit();
}
}
add_action( 'template_redirect', 'wpse375877_redirect_to_referrer' );
I’m not 100% sure if I should be using urlencode() on these URLs or not.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0