Skip to content

pre_get_posts

Ronald Huereca edited this page Jan 20, 2015 · 5 revisions

The following are examples of pre_get_posts

JetPack Portfolio Module - Sorting Archives

The following will sort the jetpack-portfolio post type on the post type's archive page.

add_action( 'pre_get_posts', 'custom_jetpack_portfolio_archive' );
function custom_jetpack_portfolio_archive( $query ) {
	if ( !$query->is_main_query() || is_admin() ) return;
	if ( $query->is_post_type_archive( 'jetpack-portfolio' ) ) {
		$query->set( 'orderby', 'menu_order, title' );
		$query->set( 'order', 'ASC' );
	}
}

Jetpack Portfolio Module - Sorting Custom Queries

The following will sort any custom queries using the jetpack-portfolio post type.

add_action( 'pre_get_posts', 'custom_jetpack_post_type_reorder' );
function custom_jetpack_post_type_reorder( $query ) {
	if ( is_admin() || $query->is_main_query() ) return;
	if ( 'jetpack-portfolio' == $query->get( 'post_type' ) ) {
		$query->set( 'orderby', 'menu_order, title' );
		$query->set( 'order', 'ASC' );
	}
}

Jetpack Portfolio Module - Sorting All Queries

The following will sort all queries using the jetpack-portfolio post type, including archives.

add_action( 'pre_get_posts', 'custom_jetpack_post_type_reorder' );
function custom_jetpack_post_type_reorder( $query ) {
	if ( is_admin() ) return;
	if ( 'jetpack-portfolio' == $query->get( 'post_type' ) ) {
		$query->set( 'orderby', 'menu_order, title' );
		$query->set( 'order', 'ASC' );
	}
}