admin管理员组文章数量:1320601
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 :-)
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 :-)
Share Improve this question edited Oct 3, 2020 at 19:39 lennartoester asked Oct 3, 2020 at 15:48 lennartoesterlennartoester 131 silver badge4 bronze badges 1 |1 Answer
Reset to default 0Assuming 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.
本文标签: How to create a filter and add query params to all links
版权声明:本文标题:How to create a filter and add query params to all links 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742083859a2419859.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
ID
the post ID or something different? What have you tried? – Howdy_McGee ♦ Commented Oct 4, 2020 at 1:57