Support » Fixing WordPress » Sorting by post type in a tag archive (archive.php)

  • Hello!

    I am using a plugin that allows me to tag pages.

    On the archive page that displays all the posts and pages for a particular tag, I would like to order entries by post type.

    I. e. I would like to list all pages first, then the posts.

    Is this possible in archive.php? If so, could you please point me in the right direction?

    Thank you very much!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Have you find a solution for this one?

    Unfortunately not! Do you have the same problem?

    This need has just aroused, so started looking for solution.
    Of course, it can be done with separating to multiple loop queries on the archive-{cpt}.php to handle each cpt for itself, but I want first to try and find a wiser solution for this.

    Ok, I found a solution.
    There’s this plugin that adds support for orderby by post__in.
    I’ve just tweaked it a bit and added support for orderby post_type

    Add this code to your functions.php file

    function tc_tag_for_cpt($query) {
      if(is_tag() && empty( $query->query_vars['suppress_filters'] ) && !is_admin()) {
    	$post_type = get_query_var('post_type');
    	$post_type = ($post_type) ?  $post_type : array('services','post','news'); //,'nav_menu_item'
    	return $query;
    add_filter( 'posts_orderby', 'sort_query_by_post_type', 10, 2 );
    function sort_query_by_post_type( $sortby, $thequery ) {
    	if(is_tag() && empty( $query->query_vars['suppress_filters'] ) && !is_admin()) {
    		if ( !empty($thequery->query_vars['post_type']) && isset($thequery->query_vars['orderby']) && $thequery->query_vars['orderby'] == 'post_type' )
    			$sortby = "find_in_set(post_type, '" . implode( ',', $thequery->query_vars['post_type'] ) . "')";
    	return $sortby;

    In the first function you will find this –

    Pass there the post_types you want by the order you want (i.e. – post, page, any_cpt)
    My function will do this only on tag pages, but you can change the is_tag functions to is_archive if you want this on all archive type.

    Hope you’ll enjoy this 🙂

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Sorting by post type in a tag archive (archive.php)’ is closed to new replies.