Wordpress

WordPress – Controlling content within the loop

When the content to be shown needs to be modified, the query used by the ‘loop’ is adjusted to suit. For example, if it was desirable to have only a specific category on the home page…

Do not use ‘query_posts‘. Apart from an increase in load time, it is known to cause problems in plugins, pagination and elsewhere.

Best practice in most situations is to write a function to adjust the main query and then attach that function to the ‘pre_get_posts‘ hook. For example:

add_action('pre_get_posts','list_solutions_only_query');
function list_solutions_only_query($query) {
	// Check the correct query/loop is being modified
	if ( $query -> is_home() && $query -> is_main_query()  )
	{
 		// Category ids to remove: blog-22, Obsolete-31
		$query->set( 'cat', '-22,-31' );
	}
		//we remove the actions hooked on the '__after_loop' (post navigation)
		remove_all_actions ( '__after_loop');	
}

Note: Many loops/queries can be used in a typical WordPress site so need to determine the correct query is being modified by adding conditions to check for suitability.

Leave a Reply

Your email address will not be published. Required fields are marked *