WordPress.org

Ready to get started?Download WordPress

Forums

Sorting by post type in a tag archive (archive.php) (5 posts)

  1. zeitschichten
    Member
    Posted 3 years ago #

    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!

  2. maorb
    Member
    Posted 3 years ago #

    Have you find a solution for this one?

  3. zeitschichten
    Member
    Posted 3 years ago #

    Unfortunately not! Do you have the same problem?

  4. maorb
    Member
    Posted 3 years ago #

    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.

  5. maorb
    Member
    Posted 3 years ago #

    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'
        $query->set('post_type',$post_type);
    	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()) {
    		$thequery->set('orderby','post_type');
    
    		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 -
    array('services','post','news')

    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 :)

Topic Closed

This topic has been closed to new replies.

About this Topic