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();
Related
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();
I have about 25,000 posts here (and rising). All of them under a Custom Post Type "lead".
Each post has meta information, including a variable called "uniqid".
this uniqid is a url parameter. now i need the post id where exactly this uniqid exists.
Now my question is if there is a way to speed up this determination.
I have tried 2 ways once a wp_query and get_results.
I ask because this function that determines the post id is always noted by plugin "query monitor" that it is slow.
These are the 2 approaches, both work. I just wonder if it is possible to speed up here?
The WP_Query solution.
$post_id = false;
$args = array(
'posts_per_page' => -1,
'post_type' => 'lead',
'fields' => 'ids',
'orderby' => 'date',
'order' => 'ASC',
'post_status' => 'publish',
'meta_key' => 'uniqid',
'meta_value' => $uniqid
);
$query = new WP_Query( $args );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// Get Post ID for return
$post_id = get_the_id();
// Break loop, when matching id was found
$uniqidGPM = get_post_meta( $post_id, 'uniqid' , true );
if($uniqidGPM == $uniqid) {
$post_found = true;
break;
}
}
}
wp_reset_postdata();
return $post_id;
The select get_results solution.
$post_id = false;
global $wpdb;
$selectQuery = "SELECT wp_wkdm_posts.ID FROM wp_wkdm_posts INNER JOIN wp_wkdm_postmeta ON ( wp_wkdm_posts.ID = wp_wkdm_postmeta.post_id ) WHERE 1=1 AND ( ( wp_wkdm_postmeta.meta_key = 'uniqid' AND wp_wkdm_postmeta.meta_value = '".$uniqid."' )) AND wp_wkdm_posts.post_type = 'lead' AND ((wp_wkdm_posts.post_status = 'publish')) GROUP BY wp_wkdm_posts.ID ORDER BY wp_wkdm_posts.post_date ASC";
$selectQueryResult = $wpdb->get_results($selectQuery);
if (empty($selectQueryResult)) {
return $post_id;
}else{
$post_id = $selectQueryResult[0]->ID;
return $post_id;
};
Please use this meta_query condition on the same query, it helps you.
$args = array(
'post_type' => 'lead',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
'key' => 'uniqid',
'value' => 'YOUR_VALUE'
)
);
$query = new WP_Query($args);
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']);
}
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();
I'm calling two different post types in WordPress:
$args = array( 'post_type' => array('post','testimonial'), 'posts_per_page' => 6 ,
'meta_key' => 'show_on_home',
'meta_value' => true
);
$loop = new WP_Query( $args );
I want to know if there is any way to export result like this order
"post-testimonial-post-testimonial-post-testimonial"
since they are different post types I can't use normal ASC or DESC orders.
Is there any other way?
Well, I used this method to solve problem.
Wants to share if anyone need it later:
$args = array('post_type' => array('post', 'testimonial'), 'posts_per_page' => 6,
'meta_key' => 'show_on_home',
'meta_value' => true,
'orderby' => 'type',
'exclude'=>1
);
$loop = new WP_Query($args);
$posts = $loop->get_posts();
$a = $posts;
$b = array(3, 0, 4, 1,5,2); // rule indicating new key order
$c = array();
foreach($b as $index) {
$c[$index] = $a[$index];
}
$posts=$c;