Adding together results of numbers from a WP_Query - php

I've got a custom post type in Wordpress, each post within it has a custom Number field (through Advanced Custom Posts).
When the page loads, I'm performing a query to find all the records that match these args:
$args = array(
'post_type' => 'hunters',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC' ,
'meta_key'=> 'full_ name',
'meta_value'=> $email,
'meta_key'=> 'w3w_location_hit',
'meta_value'=> $w3w
);
$loop = new WP_Query( $args );
I'd like to get the value of code_checks from each record returned in the query and add them all together as a total number - i.e. "there were N code checks made in total" on the page. Is there a way to get each separate value into an array and them add them together, please?
Thank you.

You don't even need to put them into an array - Something like this should work:
// set code checks back to 0
$code_checks = 0;
$args = array(
'post_type' => 'hunters',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC' ,
'meta_key'=> 'full_ name',
'meta_value'=> $email,
'meta_key'=> 'w3w_location_hit',
'meta_value'=> $w3w
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) {
// get code checks in this iteration
$number = get_field('code_checks');
// add this iteration to total
$code_checks = $code_checks + $number;
}
// echo total
echo 'There were ' . $code_checks . ' checks made in total';
/* Restore original Post Data */
wp_reset_postdata();

Related

WordPress: Combine two loops with different amount of posts

I want to show a random selection of 4 new products in WooCommerce.
For that I'm using a first loop to get the 20 newest products.
Like this:
$args= array(
'post_type' => 'product',
'posts_per_page' => 20,
'orderby' => 'date',
);
Now I've a second loop to reduce the products to 4 in a random order:
$args_new = array(
'posts_per_page' => 4,
'orderby' => 'rand',
);
In the end I merge the two loops:
$final_args = array_merge( $args, $args_new );
But that doesn't work. Is there any other way to achieve it?
General knowledge
The post_type argument accept String or Array.
Argument
Description
post_type
(String/Array) – use post types. Retrieves posts by post types, default value is post. If tax_query is set for a query, the default value becomes any.
Source # https://developer.wordpress.org/reference/classes/wp_query/#post-type-parameters
Merging queries
In crude terms we want to combine 2 posts queries, retrieve each posts ID, push them to a new array and open a new query.
Keep in mind that if you want your 4 posts to be random (as you stated in the comments) they might be some duplicates of the last 20 from the first query. Don't forget to offset the second query.
<?php
// First query
$args_1 = get_posts( array(
'post_type' => 'dogs',
'post_status' => 'publish',
'post_count' => 20,
) );
// Second query
$args_2 = get_posts( array(
'post_type' => 'dogs',
'post_status' => 'publish',
'post_count' => 4,
'offset' => 20,
'orderby' => RAND,
) );
// Merge queries
$posts = array_merge( $args_1, $args_2 );
// Push posts IDs to new array
$identifiers = array();
foreach ( $posts as $post ) {
array_push( $identifiers, $post->ID );
};
// Third query
$query = new WP_Query( array(
'post_status' => 'publish',
'post_count' => 24,
'post_in' => array_unique( $identifiers ),
) );
var_dump( $query );

Ordering by multiple parameters in a custom WordPress query loop

I've implemented an infinite scroll and in search results upon ordering by price or any custom value it doesn't work.
Here inside my enqueued script:-
isset($_GET['orderby'])?$ga_order_by = $_GET['orderby']: $ga_order_by = '';//grabbing the orderby value
if( gettype($result) == 'object') {
$ga_wp_query = new \WP_Query([ 'post_type'=> ['product_variation', 'product'], 'post__in' => $includes, 'orderby' => ['post__in',$ga_order_by], 'order' => 'ASC' ]);//so i'm ordering by search results and dynamically grabbed value.
} else {
$ga_wp_query = new \WP_Query([ 'post_type'=> 'product', 'post__in' => $includes, 'orderby' => ['post__in',$ga_order_by], 'order' => 'ASC']);
}
$args['ga_search_posts'] = json_encode($ga_wp_query->query_vars);
Inside my ajax handling function call upon search:-
$search_query = json_decode( stripslashes( $_POST['search_posts'] ), true );//this is the $args['ga_search_posts'] i'm posting via my javascript
$search_query['post_status'] = 'publish';
$search_query['posts_per_page'] = get_option('posts_per_page');
$search_query['paged'] = $_POST['page'] + 1;
wc_set_loop_prop( 'total', $_POST['search_count'] );
add_filter( 'woocommerce_get_price_html', 'labtag_show_price' );
ob_start();
query_posts( $search_query);
if ( have_posts() ) {//product loop
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
wc_get_template_part( 'content', 'product' );
}
}
}
$data = ob_get_clean();
die($data);
exit;
This works except if I try to order by any parameter say price etc. Can't 'orderby' => ['post__in',$ga_order_by] declared like an array?If not should I be passing all my posts ids to the ajax handler iterate them and sort them (if this is the case, how to handle my custom order_by params)?
https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
So, with WordPress' OrderBy, you have a couple of different options.
If you want both parameters to be sorted in the same direction of ASC or DESC, then the argument anticipates a single string, with the parameters separated by a space.
Multiple 'orderby' values Display pages ordered by 'title' and
'menu_order'. (title is dominant):
$args = array(
'post_type' => 'page',
'orderby' => 'title menu_order',
'order' => 'ASC',
);
$query = new WP_Query( $args );
You use an array when you are sorting each parameter differently:
Multiple 'orderby' values using an array
> Display pages ordered by 'title' and 'menu_order' with different sort
> orders (ASC/DESC) (available since Version 4.0):
$args = array(
'orderby' => array( 'title' => 'DESC', 'menu_order' => 'ASC' )
);
$query = new WP_Query( $args );
In your case, since you are using a variable, consider building the string and then using this within your arguments array, i.e.:
//start with a space, then .= to concatenate the $_GET parameter with the space if it's set, or clear the string if it's not.
$ga_order_by = " ";
isset($_GET['orderby'])?$ga_order_by .= $_GET['orderby']: $ga_order_by = '';
//grabbing the orderby value and building our complete string.
$orderBy = 'post__in'.$ga_order_by;
if (gettype($result) == 'object') {
$ga_wp_query = new \WP_Query([ 'post_type'=> ['product_variation', 'product'], 'post__in' => $includes, 'orderby' => $orderBy , 'order' => 'ASC' ]);//so i'm ordering by search results and dynamically grabbed value.
} else {
$ga_wp_query = new \WP_Query([ 'post_type'=> 'product', 'post__in' => $includes, 'orderby' => $orderBy, 'order' => 'ASC']);
}

Custom Post Type Get Url Loop ShortCode

I have a PHP script here I can't seem to wrap my head around, im basically trying to create a shortcode that displays the next custom post type url, then when the current post is also the last post, it loops back pulling the url to the first post.
everything works except for when you are on the final post, the shortcode displays the ID of the current post (final post) instead of the url of the first post, I am assuming it has something to do with " 'fields' => 'ids' " but i have no idea as I don't write php:
function next_post_url() {
$next_post = get_next_post();
if(!$next_post){
$args = array(
'numberposts' => 1,
'post_type' => 'portfolio',
'order' => 'ASC',
'fields' => 'ids'
);
$first_post = get_posts( $args );
$next_post_url = $first_post[0];
}
else{
$next_post_url = get_next_post()->post_title;
}
return get_permalink($next_post->ID);}add_shortcode( 'next_post_url', 'next_post_url' );
Here you go please modify your php code as shown below.
function next_post_url() {
$next_post = get_next_post();
if (!$next_post) {
$args = array(
'numberposts' => 1,
'post_type' => 'portfolio',
'order' => 'ASC',
'fields' => 'ids'
);
$first_post = get_posts($args);
$post = $first_post[0];
} else {
$post = $next_post;
}
return get_permalink($post);
}
add_shortcode('next_post_url', 'next_post_url');

How can I see when a coupon is created in WooCommerce?

I am writing a custom plugin and I need to automatically send information about every newly created coupon. Until now, I can only choose a specific coupon by its name(e.g. 1234):
$coupon = new WC_Coupon("1234");
But I cannot seem to find how to get a coupon right after its created, without knowing its name, or at least how to get all of the available coupons. Can someone help?
May be this might help. Tested and it's working. This will return all coupons since coupons are saved as post_type shop_coupon.
$args = array(
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish',
);
$coupons = get_posts( $args );
Try to get using custom post type or directly mysql query.
1) Using mysql query
// Run a query on the postmeta table to get the id of every coupon that has the email in the customer_email restrictions
$couponlist = $wpdb->get_results("SELECT
`wp_postmeta`.`post_id`
FROM `wp_postmeta`
WHERE `wp_postmeta`.`meta_key` LIKE 'customer_email'
AND `wp_postmeta`.`meta_value` LIKE '%".$email."%'");
$couponarrayfinal = array( ); //Create an array of the ids so we can use wp_query to more quickly grab the data
// Add the ids to the array in a foreach loop
foreach( $couponlist as $key => $row) {
$value = $row->post_id;
$couponarrayfinal[] = $value ;
}
2) Using get_posts method
$arg = array(
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish');
$coupons_list = get_posts( $arg );
Try with this you will get the all the data
// WP_Query arguments
$args = array(
'post_type' => array('shop_coupon'),
'post_status' => array('publish'),
'posts_per_page' => '-1',
'order' => 'DESC',
'orderby' => 'id',
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// do something
$coupon = new WC_Coupon(get_the_ID());
$coupnCode = $coupon->code;
$coupnAmount = $coupon->amount;
$minAmount = wc_format_decimal($coupon->minimum_amount, 2);
$maximumAmount = wc_format_decimal($coupon->maximum_amount, 2);
$expire = $coupon->expiry_date;
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();

wordpress wp_query not working with post_parent

The wp_query below does not work when using the post_parent operator.
If I remove this option the query runs but when I add back in, it does not.
I have identified the post parent id from the category URL in the admin and it's definitely correct with 24 posts in that category.
the url for the category is wp-admin/term.php?taxonomy=category&tag_ID=2893&post_type=post&wp_http_referer=%2Fwp-admin%2Fedit-tags.php%3Ftaxonomy%3Dcategory
<?php
// WP_Query arguments
$args = array(
'post_parent' => '2893',
'post_type' => 'post',
//'post_status' => array( 'publish' ),
//'nopaging' => true,
// 'order' => 'ASC',
// 'orderby' => 'title'
);
// The Query
$sizes = new WP_Query( $args );
// The Loop
if ( $sizes->have_posts() ) {
while ( $sizes->have_posts() ) {
$sizes->the_title();
}
} else {
echo 'nothing here...';
}
// Restore original Post Data
wp_reset_postdata(); ?>
If you want to list pages that are tagged with a category term (by id) you will have to use 'category__in' => array() instead.
The post_parent argument is for getting pages ( or CPTs that are hierarchical ) where the ID passed is the page/post which is set as parent to other pages.
Example usage of getting posts tagged with category id:
$args = array(
'category__in' => array($cat_id_1, $cat_id_2) // Where $cat_id_x is an integer of the category ID (2893 in your case).
);
Pass the argument as an integer, not a string ;)
<?php
// WP_Query arguments.
$args = array(
'post_parent' => 2893, // This should be integer.
'post_type' => 'post',
// 'post_status' => array( 'publish' ),
// 'nopaging' => true,
// 'order' => 'ASC',
// 'orderby' => 'title',
);
// The Query.
$sizes = new WP_Query( $args );
// The Loop.
if ( $sizes->have_posts() ) {
while ( $sizes->have_posts() ) {
$sizes->the_title();
}
} else {
echo 'nothing here...';
}
// Restore original Post Data.
wp_reset_postdata();

Categories