Created
January 22, 2025 12:44
-
-
Save Crocoblock/319a78f7e78b6edd8782c09ee08ffadc to your computer and use it in GitHub Desktop.
JetEngine - Query Results with empty items
This file contains hidden or 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
<?php | |
add_action( 'jet-engine/register-macros', function() { | |
/** | |
* Return purchased products. | |
*/ | |
class Query_Results_Macro_With_Empty_Items extends \Jet_Engine\Query_Builder\Macros\Query_Results_Macro { | |
public function macros_tag() { | |
return 'query_results_with_empty_items'; | |
} | |
public function macros_name() { | |
return esc_html__( 'Query Results (with empty fields)', 'jet-engine' ); | |
} | |
public function macros_callback( $args = array() ) { | |
$query_id = ! empty( $args['query_id'] ) ? $args['query_id'] : false; | |
$result_type = ! empty( $args['result_type'] ) ? $args['result_type'] : 'ids'; | |
if ( ! $query_id ) { | |
return array(); | |
} | |
$query = \Jet_Engine\Query_Builder\Manager::instance()->get_query_by_id( $query_id ); | |
if ( ! $query ) { | |
return array(); | |
} | |
$items = $query->get_items(); | |
if ( empty( $items ) || ! is_array( $items ) ) { | |
return false; | |
} | |
switch ( $result_type ) { | |
case 'ids': | |
$items = array_map( function( $item ) { | |
return jet_engine()->listings->data->get_current_object_id( $item ); | |
}, $items ); | |
break; | |
case 'selected': | |
$result_fields = ! empty( $args['result_fields'] ) ? $args['result_fields'] : ''; | |
$result_fields = explode( ',', $result_fields ); | |
$items = array_map( function( $item ) use ( $result_fields ) { | |
if ( ! $result_fields ) { | |
return $item; | |
} | |
if ( 1 === count( $result_fields ) ) { | |
$field = trim( $result_fields[0] ); | |
return isset( $item->$field ) ? $item->$field : false; | |
} else { | |
$result = array(); | |
$item = get_object_vars( $item ); | |
foreach ( $result_fields as $field ) { | |
$field = trim( $field ); | |
$result[ $field ] = isset( $item[ $field ] ) ? $item[ $field ] : false; | |
} | |
} | |
return $result; | |
}, $items ); | |
break; | |
} | |
return ! empty( $items ) ? $items : false; | |
} | |
} | |
new Query_Results_Macro_With_Empty_Items(); | |
}, 11 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment