Add Snippet To Project
Working with URLs and redirections can be a daunting task, especially if you’re new to WordPress. However, there are a number of potential reasons as to why you would want to redirect users to a URL from a title; it can be something as simple as wanting to guide your users to a linked external resource, or maybe directing them to a related post within your own website. In this article, we will explore the method of implementing this functionality effectively, ensuring you can offer a flawless and efficient browsing experience for your visitors.
function wpturbo_redirect_from_title( $url, $post ) {
if ( 'title' == $post->post_name ) {
return home_url( 'your-target-url' );
}
return $url;
}
add_filter( 'post_type_link', 'wpturbo_redirect_from_title', 10, 2 );
The given code snippet is directed towards altering the default behavior of WordPress when clicking a post based on its title.
In this context, the WordPress function wpturbo_redirect_from_title($url, $post) has been defined. This function takes in two arguments, $url and $post.
Here, $url encapsulates the post’s default URL, and $post is an object that contains all the details for the post. Within the function, an if condition checks if the post_name (slug) of the $post object is equal to 'title'.
if ( 'title' == $post->post_name )
This if condition basically determines if the specific post’s slug is set to ‘title’. In case it is set to ‘title’, the function will return another URL, overwriting the original post’s URL.
return home_url( 'your-target-url' );
Here, the home_url() is a built-in WordPress function that gets the URL of the home page for the site. It is being concatenated with ‘your-target-url’, which should be the path where you want to send users when they click on the title.
If the if condition does not hold true and the post_name is not equal to ‘title’, the function will return the original $url for the post.
return $url;
Finally, the defined wpturbo_redirect_from_title($url, $post) function gets added into WordPress’s post_type_link filter hook.
add_filter( 'post_type_link', 'wpturbo_redirect_from_title', 10, 2 );
The add_filter is a WordPress function to hook a function or method on a specific filter action. ‘post_type_link’ is the name of the filter to hook the function to. This makes WordPress call our custom function every time it is fetching the post’s permalink.
‘wpturbo_redirect_from_title’ is the name of the function to be called when the filter event fires.
’10’ is the priority for calling this function. A lower number means high priority, whereas a higher number implies low priority. If not set, WordPress sets it to 10 by default.
Lastly, the number ‘2’ denotes the number of arguments the function accepts, which aligns with the input parameters $url and $post.
This code will efficiently ensure redirection from the post with a slug as ‘title’ in WordPress, enhancing user navigation control.
