WooCommerce wc_get_orders() caching - php

I have a customer service area where the user can view orders from the front-end (if user has shop_manager role).
The orders are retrieved via the wc_get_orders function. I am attempting to sort these orders, via ajax from this page, but it seems that the order query is being cached? I can get one ajax sort to happen, but then that seems to be cached and can't be bypassed. I could be wrong, but I'm using basically the exact same setup with retrieving/sorting users, using WP_User_Query, and it will sort all day.
User orders endpoint
add_action( 'woocommerce_account_user-orders_endpoint', 'child_account_user_orders_endpoint_template' );
function child_account_user_orders_endpoint_template() {
$user_id = get_current_user_id();
if ( $user_id <= 0 ) {
return;
}
$args = array();
$qvar = get_query_var( 'only_completed', 0 );
$qvar = $qvar === 0 ? false : true;
if ( $qvar === true ) {
$args['status'] = array( 'wc-completed' );
$args['only_completed'] = true;
}
wc_get_template( 'myaccount/form-user-orders.php', $args );
}
form-user-orders.php
...
// Orders statuses
$statuses = wc_get_order_statuses();
unset( $statuses['wc-completed'], $statuses['wc-cancelled'] );
$orderby = 'date';
$order = 'DESC';
$default_args = array(
'status' => array_keys( $statuses ),
'limit' => $per_page,
'paginate' => true,
'paged' => $paged,
'date_after' => $date,
'orderby' => $orderby,
'order' => $order
);
$args = ! empty( $args ) ? $args : null;
$args = ( null !== $args ) ? array_merge( $default_args, $args ) : $default_args;
$results = wc_get_orders( $args );
Ajax to happen after clicking sort arrows
$.ajax({
type: 'post',
url: localized.ajax_url,
data: {
'action': 'user_management_sorting',
'orderby': orderBy,
'order': order,
'only_completed': only_completed,
'endpoint': shop_managers_form.managersForm.data( 'endpoint' )
},
dataType: 'json',
beforeSend: function(response){
shop_managers_form.managersForm.find( 'th.sortable' ).removeClass( 'sorted' );
shop_managers_form.globalAjaxLoader.fadeIn(400);
},
complete: function(response){
shop_managers_form.globalAjaxLoader.fadeOut(400);
},
success: function(response){
console.log( response );
shop_managers_form.managersForm.find( '.response-area' ).html('').html( response.html );
$( '#' + sortingHeader.attr( 'id' ) ).addClass( 'sorted' ).attr( 'data-order', shop_managers_form.next_order( order ) );
}
});
Ajax action
add_action( 'wp_ajax_user_management_sorting', 'child_user_management_sorting_response' );
add_action( 'wp_ajax_nopriv_user_management_sorting', 'child_user_management_sorting_response' );
function child_user_management_sorting_response() {
ob_start();
$orderby = $_POST['orderby'];
$order = ! empty( $_POST['order'] ) ? $_POST['order'] : 'ASC';
$only_completed = json_decode( $_POST['only_completed'] );
$base = wc_get_endpoint_url( $_POST['endpoint'], '', get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) );
$args = array(
'orderby' => $orderby,
'order' => $order,
'from_ajax' => true,
'base_url' => $base
);
if ( $only_completed === true ) {
$args['status'] = array( 'wc-completed' );
$args['only_completed'] = true;
}
if ( 'user-management' === $_POST['endpoint'] ) {
$uses_meta = array( '_quickbooks_account_no', 'billing_company', 'authorized_user_status' );
if ( in_array( $orderby, $uses_meta ) ) {
$args['orderby'] = 'meta_value';
$args['meta_key'] = $orderby;
}
}
wc_get_template( 'myaccount/form-' . $_POST['endpoint'] . '.php', $args );
$html = ob_get_clean();
if ( ! empty( $html ) ) {
$message = 'success';
} else {
$html = '';
$message = 'failure';
}
echo json_encode( array(
'message' => $message,
'html' => $html
));
wp_die();
}
I can make things semi-work by accessing these straight from the database via $wpdb->get_results() but I don't really want to figure out the whole raw sql for joining all the tables, then trying to access all the order info that I need this way..
Any ideas to get around the caching of wc_get_orders or alternative methods to accomplish this?

Related

Relating Wordpress Users with Order Export

We are using Advanced Custom Fields, WP All Export Pro, and WordPress with Woocommerce.
I have an ACF field created for our accountant in users area of WordPress called "traverse_customer_id". This is for her to know what customer this order is for.
I have this ACF field showing in the orders export but the data comes back blank on each export. I think it's because I'm not relating the order with the customer or user ID. I've attempted to use a code snippet from WP All Exports' support without any luck. Could anyone with knowledge help me see what I'm doing wrong?
This is what I have in the "Custom export field" area: (I think this is running the function on each line of the import.)
[sf_helper_meta_query_lookup("traverse_customer_id",{Customer User ID},"user")]
Then I have this below in the Function Editor:
function sf_helper_meta_query_lookup( $meta_key = '', $meta_value = '', $object_type = 'post', $taxonomy = '', $return_field = 'ID', $compare = '=', $custom_args = array() ) {
if ( empty( $object_type ) || empty( $meta_key ) || empty( $meta_value ) ) return;
$func = 'get_posts';
switch ( $object_type ) {
case 'user':
$func = 'get_users';
break;
case 'term':
$func = 'get_terms';
if ( $return_field == 'ID' ) {
$return_field = 'term_id';
}
break;
default:
$func = 'get_posts';
break;
}
if ( ! empty( $custom_args ) ) {
$objects = $func( $custom_args );
if ( ! empty( $objects ) ) {
return $objects[0]->$return_field;
} else {
return false;
}
}
$args = array();
$meta_query = array( array(
'key' => $meta_key,
'value' => $meta_value,
'compare' => $compare
) );
if ( $func == 'get_terms' ) {
$args = array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'meta_query' => $meta_query
);
} elseif ( $func == 'get_users' ) {
$args = array(
'meta_query' => $meta_query
);
} else {
$args = array(
'post_type' => $object_type,
'meta_query' => $meta_query
);
}
if ( $objects = $func( $args ) ) {
return $objects[0]->$return_field;
} else {
return false;
}
}
Any help would be greatly appreciated!

add "duplicate" to custom post type admin menu

I'm trying to add the "duplicate" post option to my custom post type admin menu called events. I have searched online, but there is very little documentation on how to add this function to the custom post types. Perhaps I am using the incorrect terminology when searching.
The code below adds the "duplicate" function, but when clicked it doesn't actually duplicate the post but returns a white screen instead. Are there any pointers or tips that you can give me?
function rd_duplicate_post_link( $actions, $post ) {
if (current_user_can('edit_posts') || $post->post_type=='events') {
$actions['duplicate'] = 'Duplicate';
}
return $actions;
}
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2)
You need to call admin_action_rd_duplicate_post_as_draft hook
function rd_duplicate_post_link( $actions, $post ) {
//print_r($actions);
//if (current_user_can('edit_posts') || $post->post_type=='movies') {
$actions['duplicate'] = 'Duplicate';
// }
return $actions;
}
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2);
add_action( 'admin_action_rd_duplicate_post_as_draft', 'dt_dpp_post_as_draft' );
function dt_dpp_post_as_draft()
{
global $wpdb;
/*sanitize_GET POST REQUEST*/
$post_copy = sanitize_text_field( $_POST["post"] );
$get_copy = sanitize_text_field( $_GET['post'] );
$request_copy = sanitize_text_field( $_REQUEST['action'] );
$opt = get_option('dpp_wpp_page_options');
$suffix = !empty($opt['dpp_post_suffix']) ? ' -- '.$opt['dpp_post_suffix'] : '';
$post_status = !empty($opt['dpp_post_status']) ? $opt['dpp_post_status'] : 'draft';
$redirectit = !empty($opt['dpp_post_redirect']) ? $opt['dpp_post_redirect'] : 'to_list';
if (! ( isset( $get_copy ) || isset( $post_copy ) || ( isset($request_copy) && 'dt_dpp_post_as_draft' == $request_copy ) ) ) {
wp_die('No post!');
}
$returnpage = '';
/* Get post id */
$post_id = (isset($get_copy) ? $get_copy : $post_copy );
$post = get_post( $post_id );
$current_user = wp_get_current_user();
$new_post_author = $current_user->ID;
/*Create the post Copy */
if (isset( $post ) && $post != null) {
/* Post data array */
$args = array('comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $new_post_author,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => $post_status,
'post_title' => $post->post_title.$suffix,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);
$new_post_id = wp_insert_post( $args );
$taxonomies = get_object_taxonomies($post->post_type);
if(!empty($taxonomies) && is_array($taxonomies)):
foreach ($taxonomies as $taxonomy) {
$post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);}
endif;
$post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
if (count($post_meta_infos)!=0) {
$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
foreach ($post_meta_infos as $meta_info) {
$meta_key = $meta_info->meta_key;
$meta_value = addslashes($meta_info->meta_value);
$sql_query_sel[]= "SELECT $new_post_id, '$meta_key', '$meta_value'";
}
$sql_query.= implode(" UNION ALL ", $sql_query_sel);
$wpdb->query($sql_query);
}
/*choice redirect */
if($post->post_type != 'post'):$returnpage = '?post_type='.$post->post_type; endif;
if(!empty($redirectit) && $redirectit == 'to_list'):wp_redirect( admin_url( 'edit.php'.$returnpage ) );
elseif(!empty($redirectit) && $redirectit == 'to_page'):wp_redirect( admin_url( 'post.php?action=edit&post=' . $new_post_id ) );
else:
wp_redirect( admin_url( 'edit.php'.$returnpage ) );
endif;
exit;
} else {
wp_die('Error! Post creation failed: ' . $post_id);
}
}

Filter posts by one meta_key and two meta_value in WordPress using a select element with Ajax

THIS POST IS GOING TO BE LONG so bear with me, please!.
I'm trying to build a custom page which will be used as a "directory" for two post types that I have created in the back end.
This is what I'm trying to build:
So far I already have a function which is too large but it does the work(or at least almost).
So I will begin by posting the HTML file and then I will share the functions that I'm using with the custom page:
<?php
/*
Template Name: Buscador Avanzado
Template Post Type: page
*/
?>
<?php get_header(); ?>
<div class="container">
<div class="row">
<?php echo get_breadcrumb(); ?>
<div id="my-adv-search">
<!-- Post Type -->
<div class="col-md-3">
<div class="form-group">
<label for="q_post_type">Tipo</label>
<select class="form-control" id="q_post_type">
<option selected>Selecciona una opcion</option>
<?php
$args = array(
'public' => true,
'_builtin' => false,
);
$post_types = get_post_types($args);
foreach( $post_types as $post_type ) {
echo '<option>' . $post_type . '</option>' ;
}
?>
</select>
</div>
</div>
<!-- Genero -->
<div class="col-md-3">
<div class="form-group">
<label for="q_taxonomy">Genero</label>
<select class="form-control" multiple id="q_taxonomy">
<option value="any" selected>Selecciona una opcion</option>
<?php
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names'; // or objects
$operator = 'and'; // 'and' or 'or'
$taxonomies = get_taxonomies( $args, $output, $operator );
if ( $taxonomies ) {
foreach ( $taxonomies as $taxonomy ) {
echo '<option>' . $taxonomy . '</option>';
}
}
?>
</select>
</div>
</div>
<!-- Estado -->
<div class="col-md-3">
<div class="form-group">
<label for="q_orderby">Estado</label>
<select class="form-control" id="q_orderby">
<option value="any" selected>Selecciona una opcion</option>
<?php
foreach ( [
'author' => 'Author',
'comment_count' => 'Popularity (# of Comments)',
//'year' => 'Year',
'en_emision' => 'Emision',
'en_final' => 'Finalizado',
//'views_count' => 'Views',
//'order' => 'ASC ? DESC',
] as $value => $label ) {
printf( '<option value="%s">%s</option>',
esc_attr( $value ), esc_html( $label ) );
}
?>
</select>
</div>
</div>
<!-- Year -->
<div class="col-md-3">
<div class="form-group">
<label for="q_year">Año</label>
<select class="form-control" id="q_year">
<option value="any" selected>Selecciona una opcion</option>
<?php
$args = array(
'public' => true,
'_builtin' => false,
'type' => 'yearly',
'format' => 'option',
);
wp_get_archives($args);
?>
</select>
</div>
</div>
<!-- Nonce field. -->
<?php wp_nonce_field( 'my-adv-search', 'q_nonce' ); ?>
<!-- Search Button -->
<div class="col-md-12">
<input type="submit" class="btn btn-success" id="buscar_btn" value="Search">
<br><br>
<noscript><b>Tu buscador no soporta Javascript, haciendo imposible mostrar los posts.</b></noscript>
<div id="resultados"><div class="cargando_medio"></div></div>
</div>
</div><!-- End #my-adv-search -->
</div>
</div>
<?php get_footer(); ?>
<script type="text/javascript">
jQuery( function( $ ){
var ajaxurl = '/wptests/wp-admin/admin-ajax.php';
function searchPosts( btn ) {
var _btn_text = btn.value;//, q_order;
btn.disabled = true;
btn.value = 'Searching..';
// q_order = $( '#q_order-asc' ).is( ':checked' ) ?
// 'ASC' : 'DESC';
return $.post( ajaxurl, {
action: 'my_adv_search',
q_nonce: $( '#q_nonce' ).val(),
q_post_type: $( '#q_post_type' ).val(),
q_taxonomy: $( '#q_taxonomy' ).val(),
q_year: $( '#q_year' ).val(),
q_orderby: $( '#q_orderby' ).val(),
// q_order: q_order,
} ).done( function( s ){
if ( 'session_expired' === s ) {
location.reload();
return;
}
$( '#resultados' ).html( s );
} ).always( function(){
btn.value = _btn_text;
btn.disabled = false;
} );
}
$( '#buscar_btn', '#my-adv-search' ).on( 'click', function( e ){
e.preventDefault();
// Run AJAX search.
searchPosts( this );
// Remove button focus.
this.blur();
} );
} );
</script>
Now here's the function that works with it(I pointed out where the problem is):
// Buscador Avanzado
add_action( 'wp_ajax_my_adv_search', 'ajax_my_adv_search' );
add_action( 'wp_ajax_nopriv_my_adv_search', 'ajax_my_adv_search' );
function ajax_my_adv_search() {
if ( ! check_ajax_referer( 'my-adv-search', 'q_nonce', false ) ) {
echo 'session_expired';
wp_die();
}
$post_type = isset( $_POST['q_post_type'] ) ? $_POST['q_post_type'] : '';
$taxonomy = isset( $_POST['q_taxonomy'] ) ? $_POST['q_taxonomy'] : [];
$year = isset( $_POST['q_year'] ) ? $_POST['q_year'] : '';
$orderby = isset( $_POST['q_orderby'] ) ? $_POST['q_orderby'] : [];
$order = isset( $_POST['q_order'] ) ? $_POST['q_order'] : '';
// Note that if $post_type is 'any', all post statuses will be included. In
// that case, you may want to set specific post statuses below.
$post_status = 'publish';
// by Taxonomy
$taxonomy = array_filter( (array) $taxonomy );
if ( ! in_array( 'any', $taxonomy ) ) {
$taxonomy = array_unique( array_map( 'trim', $taxonomy ) );
add_filter( 'posts_join', function( $c ) use ( $taxonomy ) {
if ( ! empty( $taxonomy ) ) {
global $wpdb;
// 1 below is one/number and not the lowercase of L
$c .= " INNER JOIN {$wpdb->term_relationships} AS ctr1 ON ctr1.object_id = {$wpdb->posts}.ID" .
" INNER JOIN {$wpdb->term_taxonomy} AS ctt1 ON ctt1.term_taxonomy_id = ctr1.term_taxonomy_id";
}
return $c;
} );
add_filter( 'posts_where', function( $c ) use ( $taxonomy ) {
if ( ! empty( $taxonomy ) ) {
$tax_list = array_map( 'esc_sql', $taxonomy );
$tax_list = "'" . implode( "', '", $tax_list ) . "'";
// 1 below is one/number and not the lowercase of L
$c .= " AND ( ctt1.taxonomy IN ($tax_list) )";
}
return $c;
} );
}
// by Custom Field Value - Metadata
$orderby = array_filter( (array) $orderby );
if ( in_array( 'any', $orderby ) ) {
// Don't sort by post date.
$orderby2 = false;
} else {
$orderby = array_unique( array_map( 'trim', $orderby ) );
// TRUE if we're sorting by year.
$ob_year = false;
foreach ( $orderby as $i => $s ) {
// Sort posts by year.
if ( 'year' === $s ) {
$ob_year = true;
unset( $orderby[ $i ] );
}
//// PROBLEM BEGINS HERE
// Sort posts by meta value en_emision from meta key estado_de_video. Note that this would only return
// posts that have the custom field 'en_emision'.
if ( 'en_emision' === $s ) {
$meta_key = 'en_emision';
$orderby2 = 'meta_value';
unset( $orderby[ $i ] );
}
// Sort posts by meta value en_final from meta key estado_de_video. Note that this would only return
// posts that have the custom field 'en_final'.
if ( 'en_final' === $s ) {
$meta_key = 'en_final';
$orderby2 = 'meta_value';
unset( $orderby[ $i ] );
}
}
//// PROBLEM ENDS HERE
add_filter( 'posts_orderby', function( $c, $q ) use ( $ob_year ) {
if ( $ob_year ) {
global $wpdb;
// Use the value parsed by WP_Query.
$order = $q->get( 'order' );
$c .= $c ? ', ' : '';
$c .= "YEAR({$wpdb->posts}.post_date) $order";
}
return $c;
}, 10, 2 );
$ok = isset( $orderby2 );
if ( ! $ok && empty( $orderby ) ) {
// Don't sort by post date.
$orderby2 = false;
} elseif ( ! $ok ) {
// Pass to WP_Query as a string.
$orderby2 = implode( ' ', $orderby );
}
}
// by Year
if ( ! is_numeric( $year ) ) {
$year = '';
}
$q = new WP_Query( [
'post_status' => $post_status,
'post_type' => array($post_type),
'posts_per_page' => -1,
'post_parent' => 0,
'year' => $year,
'meta_key' => isset( $meta_key ) ? $meta_key : '',
'orderby' => $orderby2,
'order' => $order,
] );
if ( $q->have_posts() ) {
echo '<ul>';
while ( $q->have_posts() ) {
$q->the_post();
?>
<li><?php the_title() ?></li>
<?php
}
echo '</ul>';
} else {
echo '<div class="alert alert-danger">Ningun Resultado</div>';
}
wp_die();
}
Now what I'm want is to sort post by one meta_key (estado_de_video) and two meta_values that I created for that meta key (en_emision, en_final).
Right now with the function above I tried doing something similar as if I were sorting by year but it did not work, then I tried changing the WP_Query just a bit:
This suggestion was given to me by someone trying to help:
$q = new WP_Query( [
'post_status' => $post_status,
'post_type' => array($post_type),
'posts_per_page' => -1,
'post_parent' => 0,
'year' => $year,
'orderby' => 'meta_value', //SET THIS AS REQUIRED
'order' => $order,
] );
if ( isset( $meta_key ) && '' != $meta_key ) {
$q['meta_key'] = 'estado_de_video';
$q['meta_value'] = $meta_key;
}
for what I've been told this should have worked out somehow or at least it should have returned the posts with the either meta_value (en_emision or en_final) but it didn't, then I tried to change the function by deleting the commented section(see the function snippet above) and deleting this as well:
if ( isset( $meta_key ) && '' != $meta_key ) {
$q['meta_key'] = 'estado_de_video';
$q['meta_value'] = $meta_key;
}
So once those were deleted I tried changing the WP_Query for this:
$q = new WP_Query( [
'post_status' => $post_status,
'post_type' => array($post_type),
'posts_per_page' => -1,
'post_parent' => 0,
'year' => $year,
'orderby' => 'meta_value', //SET THIS AS REQUIRED
// 'meta_key' => $meta_key,
// 'meta_value' => $meta_values,
'order' => $order,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'estado_de_video',
'value' => array('en_emision', 'en_final'),
'compare' => 'EXISTS'
),
),
] );
Still has not worked out. Can somebody guide me through this or at least tell me a better approach?
Thanks in advance.
BELOW THIS BLOCKQUOTE IS NOT NECCESARY TO HELP WITH BUT WILL BE
APPRECIATED IF SOMEBODY DECIDES TO.
I need help in the second <select>; I want the taxonomies to appear according to what post type has been selected. Example:
<select> 1 for CPTs: Peliculas,
<select> 2 : load the categories taxonomies from selected post types.
Lets say I have selected "Peliculas" then I want the all the categories that have been made in the custom taxonomy attached to the "Peliculas".
Right now I have two CPT's one that is called anime and another called peliculas
"anime" has the "categorias_anime" taxonomy,
"peliculas" has the "categorias_movie" taxonomy.
Thanks in advance.
Ordering by one given meta_value is simple, no need for complex queries.
I see you mixed up meta key and values in your given codes.
Just use this:
$q = new WP_Query( [
'post_status' => $post_status,
'post_type' => array($post_type),
'posts_per_page' => -1,
'post_parent' => 0,
'year' => $year,
'orderby' => 'meta_value',
'meta_key' => 'estado_de_video',
'order' => $order, //ASC or DESC
] );
That's all. No need to set meta_value parameter here.

Search on custom post type table

I wanted to use the default search functionality using this :
The problem is I've made this table using this line of code
function waiting_list_column_content_callback($column_name, $post_ID) {
$guestID = get_post_meta( $post_ID, 'guest', true );
$user_info = get_userdata( $guestID );
$floorplanID = get_post_meta( $post_ID, 'floorplan', true );
$notes = get_post_meta( $post_ID, 'notes', true );
$waiting_list = wpr_get_waiting_list( $floorplanID );
$list_location = wpr_get_list_location( $post_ID, wpr_get_waiting_list( $floorplanID ) );
if ( $column_name == 'fname' ) {
echo ''.$user_info->first_name.'';
}elseif ( $column_name == 'lname' ) {
echo ''.$user_info->last_name.'';
}elseif( $column_name == 'floorplan' ){
echo get_the_title($floorplanID);
}
elseif( $column_name == 'logs_print' ){
echo 'Print';
}elseif( $column_name == 'list_location' ){
echo $list_location;
}
}
I've tried this and this. It work, but I can only search the user by "id".Since "id" is the only custom_field available to use.
This is the code I'm using to get results by id. "guest" is the "id" of the user. Which I use to display the last name and the first name of the user.
function extend_admin_search( $query ) {
//Extend search for document post type
$post_type = 'wpr_waiting_list';
// Custom fields to search for
$custom_fields = array(
"guest",
);
if( ! is_admin() )
return;
if ( $query->query['post_type'] != $post_type )
return;
$search_term = $query->query_vars['s'];
// Set to empty, otherwise it won't find anything
$query->query_vars['s'] = '';
if ( $search_term != '' ) {
$meta_query = array( 'relation' => 'OR' );
foreach( $custom_fields as $custom_field ) {
array_push( $meta_query, array(
'key' => $custom_field,
'value' => $search_term,
'compare' => 'LIKE'
));
}
$query->set( 'meta_query', $meta_query );
};
}
add_action( 'pre_get_posts', 'extend_admin_search' );
What I've wanted to do was search this custom post type by "first name" or "last name" .
I've tried some sql codes but I'm getting some "headers" error I don't understand.

How to exclude a term from a taxonomy post count function

I have a function that displays the post count of any terms for its taxonomy anywhere i want to show it and it works great but i would like to change this up a bit to completely exclude the post count of any post that has a certain term added to it, let's call that "state". So if a post has "state" added to it, i would like the function to not include the count of that post in any terms within the taxonomy.
function get_city_count( $taxonomy = 'countries', $term = '', $args = [] )
{
if ( !$term )
return false;
if ( $term !== 'all' ) {
if ( !is_array( $term ) ) {
$term = filter_var( $term, FILTER_VALIDATE_INT );
} else {
$term = filter_var_array( $term, FILTER_VALIDATE_INT );
}
}
if ( $taxonomy !== 'countries' ) { $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
if ( !taxonomy_exists( $taxonomy ) ) return false;
}
if ( $args ) { if ( !is_array ) return false; } $defaults = [ 'posts_per_page' => 1, 'fields' => 'ids' ];
if ( $term !== 'all' ) { $defaults['tax_query'] = [ [ 'taxonomy' => $taxonomy, 'terms' => $term ] ]; }
$combined_args = wp_parse_args( $args, $defaults );
$q = new WP_Query( $combined_args );
return $q->found_posts;
}

Categories