Skip to content

Instantly share code, notes, and snippets.

@v-marinkov
Forked from gsgoraya/array_for_repeater.php
Created June 29, 2021 09:17
Show Gist options
  • Save v-marinkov/a2ffdf300e363cb8f543bd41bfad49e5 to your computer and use it in GitHub Desktop.
Save v-marinkov/a2ffdf300e363cb8f543bd41bfad49e5 to your computer and use it in GitHub Desktop.
<?php
/**
* A Hack to generate mock WP Post objects from any arbitrary array
* A possible use case is to render a list of taxonomy terms using Oxygen Builder's repeater element,
* as the repeater allows only WP_Query as a source of data
*
* @author: Gagan S Goraya
* @link: https://gagangoraya.com
*
*/
function gsg_override_posts_results( $posts, $query ) {
// identify the query by testing for a specific parameter, in this case the arbitrary value provided for the paramter post_type
if( 'product_cat_list' === $query->get('post_type') ) {
// And obviously, the $posts is going to be empty, lets ensure that its an empty array and not null
$posts = array();
// Lets populate it with the data that we want i.e., the terms for any arbitrary taxonomy
// get terms for any taxonomy. woo commerce product category in this case.
$terms = get_terms(
array(
'taxonomy' => 'product_cat',
'type' => 'product'
)
);
// generate mock post objects using the data from the taxonomy terms
foreach( $terms as $term ) {
$posts[] = (object) array(
'post_title' => $term->name,
'post_name' => $term->slug,
//.... you can load any other misc data here
) ;
}
}
return $posts;
}
add_filter('posts_results', 'gsg_override_posts_results', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment