Category Archives: Functions

Redirect to referring page after login

Redirect to same page

When a user logs in they are taken to the home page or to the CMS. This can be annoying sometimes.

Example 1) You want a user to fill out a form, but the form requires you to be logged in. You email out the link to the form and the client is required to log in. They are then taken to the CMS or site homepage. Now they have lost the form in the process.

Example 2) You have a Members Only Area that requires being logged in. Perhaps you have BuddyPress, BBPress, a private onine store, or any other part of your site that requires being logged in. You send someone a link to a product, a forum post, or some exclusive content, they click the link, but are asked to login. Once again they are forwarded to the CMS or homepage and have lost the original link.

Solution

Put this code into your Child Theme’s function file. From then on, you will automatically be returned to the page you were trying to access before you were asked to log in.

add_filter( 'login_redirect', function ( $redirect_to, $requested_redirect_to ) {
if ( ! $requested_redirect_to ) {
$redirect_to = wp_get_referer();
}
return $redirect_to;
}, 10, 2 );

Random Posts on your WordPress homepage

Random Posts in WordPress

WordPress by default displays posts in date order with Ascending or Descending options. What if you prefer to show random posts on your homepage so that every time someone visits your site, they see a different selection of posts.

First off, why would you want to do this. It could be that older posts on your site are just as relevant as newer posts and they don’t get read because they are buried too deep due to their date. While there are a number of plugins that offer this functionality, they usually offer this for widgets only. But what if I told you that you can do this with five lines of code.

Copy the code below and paste into your Child theme’s function file. That’s it.

add_action('pre_get_posts','alter_query');
function alter_query($query){
if ($query->is_main_query() && is_home())
$query->set('orderby', 'rand'); //Set the order to random
}