Forked from yankiara/oxygen-repeater-dynamic-query.php
Created
June 11, 2020 09:00
-
-
Save aleua/8a59ecd556222d7921673fd4920962ab to your computer and use it in GitHub Desktop.
Use dynamic queries with Oxygen's repeater
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Example of related posts repeater for any CPT with taxonomy: | |
* - Filter query to prevent altering queries inside the repeater items, | |
* - Retrieve post category slug : I have only one for each post, so I just take first element. | |
* (You might need to add error tests, of course, if you don't accept empty results, | |
* for instance if you forgot to set post category.) | |
* - Set tax_query arg with category slug | |
* - Set random order | |
* - Exclude current post | |
* - Deactivate pagination | |
*/ | |
/* Put this in a code block just BEFORE the repeater */ | |
<?php | |
function dynamic_category_query( $query ) { | |
global $post; | |
if ( $query->query['post_type'][0] == 'cpt_slug' ) { | |
$cat = wp_get_post_terms( $post->ID , 'categorie_slug', array( 'fields' => 'slugs' ) )[0]; | |
$query->set( 'tax_query', array( | |
array( | |
'taxonomy' => 'categorie_slug', | |
'field' => 'slug', | |
'terms' => $cat, | |
'include_children' => false | |
) | |
) ); | |
$query->set( 'orderby', 'rand' ); | |
$query->set( 'post__not_in', array($post->ID) ); | |
$query->set( 'no_found_rows', true ); | |
} | |
} | |
add_action( 'pre_get_posts', 'dynamic_category_query' ); | |
?> | |
/* | |
* REPEATER (use custom query and set post type and number of posts per page as you wish) | |
*/ | |
/* Put this in a code block just AFTER the repeater if you need to make other queries later on the page */ | |
<?php | |
remove_action( 'pre_get_posts', 'dynamic_category_query' ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment