• Hi Team,
    I had a thread to display my custom post archive in author and month archive ate

    I got the below code and its working fine except a bug that when I am clicking on custom post archive, I am getting my general posts below custom posts.

    Please help on this.

    add_action( 'pre_get_posts', 'include_cpt_in_archives', 100);
    function include_cpt_in_archives( $query ){
      if (
            is_admin()
            || ! $query->is_main_query()
            || ! ( $query->is_search || $query->is_archive )
        )
        return;
    
      $post_types = get_post_types( array('public'=> true, 'exclude_from_search'=> false, '_builtin' => false) );
      // add normal post
      $post_types['post'] = 'post';
    
      $query -> set('post_type', $post_types);
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter ergkranjan

    (@ergkranjan)

    Hello,
    mm I see that when there are posts with exactly the same date (day month year) the custom post is shown before general post yeah..

    Well dunno why you call it “a bug” ??
    Anyway isn’t really tied to the code above, it’s more how wordpress groups/orders posts..
    For example you can order them by the post id (date and then post_if), using this code, should work:

    add_action( 'pre_get_posts', 'a_include_cpt_in_archives', 100);
    function a_include_cpt_in_archives( $query ){
      if (
            is_admin()
            || ! $query->is_main_query()
            || ! ( $query->is_search || $query->is_archive )
        )
        return;
    
      $post_types = get_post_types( array('public'=> true, 'exclude_from_search'=> false, '_builtin' => false) );
      // add normal post
      $post_types['post'] = 'post';
    
      $query -> set('post_type', array_reverse($post_types));
    
      add_filter('posts_orderby', '_my_orderby', 20);
    }
    
    function _my_orderby( $orderby ) {
        global $wpdb;
        $_my_orderby = "{$wpdb->posts}.ID DESC";
        return $orderby ? $orderby . ',' . $_my_orderby : $_my_orderby ;
    }

    ah,
    $query -> set('post_type', array_reverse($post_types));
    that array_reverse is a type while I was doing some tests.
    this is enough:
    $query -> set('post_type', $post_types);

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Getting general posts in custom post archive’ is closed to new replies.