Skip to content

Instantly share code, notes, and snippets.

@whatsnewsisyphus
Created February 18, 2017 14:36
Show Gist options
  • Save whatsnewsisyphus/c73315fa6d3c7a0cf5ed94d31fc46ba8 to your computer and use it in GitHub Desktop.
Save whatsnewsisyphus/c73315fa6d3c7a0cf5ed94d31fc46ba8 to your computer and use it in GitHub Desktop.
Group by Post Type with Relevanssi

Do you mind exemplifying that? I'll submit the resulting code in a gist that you can share in the knowledgebase since this seems to be a frequent question in stackoverflow etc. I made some suggestions below.

Can you imagine a way where one could programmatically create the indexed array so that you don't have to declare the groups twice? For example, do the following. I'm going backwards from array keys to a string array because I don't know an easy way to create an array of arrays with keys from another string array, that would be a bit more semantically correct.

// Declare keyed arrays for hits sorting
$people_types_keyed = array( "faculty"=>array(), "staff"=>array(), "student"=>array() );
$academic_types_keyed = array ("courses"=>array(), "programs"=>array() );
$types = array_merge($academic_types_keyed, $people_types_keyed);
// insert array push code here
//merge hits back with php5 ... operator, much easier than redeclaring each key.
$hits[0]=array_merge(...$types);

// Create slug arrays from keys for later use in grouping in template, this could be moved to the template.php
$people_types = array_keys( $people_types_keyed );
$academic_types = array_keys( $academic_types_keyed );

later in template, use the slug arrays from functions in the form of

if(in_array($post->post_type, $people_types))

Though I need a bit of help here on how to separate them with headers, since we know the order of sorting from before, we could just declare while loops in the right order. If one doesn't know the order of things, I suppose you could rewind the loop at the end of each while, though I'm not sure how relevanssi would like that. Or you could get fancy and merge all groups into yet another array with Keys as the headers that you want and wrap the bottom code in a for each with the header string replaced with key() of each.

<section class="search__people">
    <h2>People</h2>
    <?php
        $groupCount = 0;
    while( have_posts() ) { // Start second while loop
      the_post();
            if (in_array($post->post_type, $people_types) {
        get_template_part( 'partials/search/search-entry' );
                $groupCount ++;
      }
    } // end second while loop
        if($groupCount == 0) {
            echo '<p>'.__('No search results in this group').'</p>';
        }
    ?>
</section>

I'm really not that great with php so it would be really great if you could help. I'm helping a school out with a website pro-bono.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment