$wpdb get_results - loop from specific category - php

I have this code, its working good, but its gets posts from all categories. I need to get posts only from category ID 2. I tried to add "AND term_taxonomy_id = 2" to my code, but this didint work. Can somebody help me with this, my code:
<?php //loops all posts
$my_query = $wpdb->get_results
("SELECT * FROM `{$table_prefix}posts`, {$table_prefix}postmeta
WHERE {$table_prefix}posts.post_status = 'publish'
AND {$table_prefix}posts.id = {$table_prefix}postmeta.post_id
AND {$table_prefix}postmeta.`meta_key` = 'wpcf-data-nuo' ORDER BY if({$table_prefix}postmeta.`meta_value` = '' or {$table_prefix}postmeta.`meta_value` is null,1,0), {$table_prefix}postmeta.`meta_value` ASC LIMIT 12");
foreach($my_query as $post) {
setup_postdata($post);
?>

Please follow below code, Hope! its working
You can define the meta key for orderby parameter using the old method (I tested on WP 3.1.1)...
query_posts(
array( 'post_type' => 'services',
'order' => 'ASC',
'meta_key' => 'some_key',
'orderby' => 'meta_value', //or 'meta_value_num'
'meta_query' => array(
array('key' => 'order_in_archive',
'value' => 'some_value'
)
)
)
);
OR
For me, I wanted to order by a numeric field and I had to use 'type' => 'NUMERIC' inside the meta query.
This issue in general is cleared up in WordPress 4.2 by using named queries. e.g.
$args = array(
'post_type' => 'services',
'orderby' => 'order_clause',
'meta_query' => array(
'order_clause' => array(
'key' => 'order_in_archive',
'value' => 'some_value',
'type' => 'NUMERIC' // unless the field is not a number
)));
Reference link for set the meta value in query: https://rudrastyh.com/wordpress/meta_query.html

You can do it by WP_QUERY instead writing custom Query.
The query to get the results and then your custom sort order by altering the WP_QUERY if default order parameters not work as expected.
$args = array(
'post_type' => 'post',
'posts_per_page' => 8,
'cat' => 2,
'meta_key' => 'wpcf-data-nuo',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
add_filter('posts_orderby', 'filter_query');
$q = new WP_Query($args);
remove_filter('posts_orderby', 'filter_query');
function filter_query( $orderby_statement ) {
global $table_prefix;
$orderby_statement .= " if({$table_prefix}postmeta.`meta_value` = '' ";
$orderby_statement .= " or {$table_prefix}postmeta.`meta_value` is null,1,0), {$table_prefix}postmeta.`meta_value`";
return $orderby_statement;
}
Note: Do not remove spaces from $orderby_statement .= because it require spaces while running query.
If it still doesn't work, then add var_dump($orderby_statement); before return $orderby_statement; then copy the SQL and add it in your question so it will help us to understand what is the issue.

Related

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']);
}

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();

Use ACF checkbox value array to find "More like this"

I'm using an ACF checkbox to designate categories (called "aims") for Psychology apps/sites. So values would be, say, "Mindfulness", "Well-Being" and "Depression".
Since it's possible to select multiple values, what I'd like to do is have a More Like This where any single post could show other posts that match one or more of the categories of the post.
UPDATE: Here's the code I'm using now, which I'm still not having any luck with:
the_field( 'aims'); /* since I'm on the page for a single post, this gives me the aims for the current post and is currently returning values from the checkbox with multiple selections (as an array, I believe) */
$args = array(
'numberposts' => -1,
'post_type' => 'program',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'aims',
'value' => 'Well-Being', /* I'd actually like this to use the aims for the current post, but I've hard-coded for testing, and am not seeing any results */
'compare' => 'IN')
));
$more_like_this = new WP_Query ($args);
while ($more_like_this->have_posts()) : $more_like_this->the_post();
$star_rating = get_field('overall_score');
?>
<?php the_title(); ?>
<?php echo $star_rating ?>
<?php endwhile;
wp_reset_query();
?>
If you need a wp query to select some posts where multiple ACF checkbox options must be checked you can do like this:
// Get the array with selected options
$fields = get_field('somefield');
// First create the meta_query variable (AND can also be OR)
$meta_query = array('relation' => 'AND');
foreach( $fields as $field ){
$meta_query[] = array(
'key' => 'name_of_acf_checkbox_here',
'value' => $aim,
'compare' => 'LIKE',
);
}
// args
$args = array(
'numberposts' => -1,
'post_type' => 'postype_here',
'meta_query' => $meta_query,
);
$the_query = new WP_Query( $args );

where clause in wordpress

I want to generate few random links for my wordpress but i don't want to use order by rand as it will cause heavy load on mysql. below links works fine but when i use orderby rand
$wprpi_arg = array(
'numberposts' => $wprpi_value['post'],
'post__not_in' => array(get_the_ID()),
// 'where ID <' => get_the_ID(),
'orderby' => 'rand',
'post_status' => 'publish',
);
i want to use this instead
$wprpi_arg = array(
'numberposts' => $wprpi_value['post'],
'post__not_in' => array(get_the_ID()),
'where ID <' => get_the_ID(),
'orderby' => 'ID',
'post_status' => 'publish',
);
But this is not working. WordPress is listing only 5 last links of table as it is orderby id its showing 5 links in desc order.
But i want to generate 5 links lower than my current id.
For example: if users is on page /10000 the generated links should be 9999,9998,9997,9996,9995 and if user is on /100 page generated links will be 99,98,97,96,95 but wordpress ignores where clause and generates same link always orderby desc limit 5 without considering where clause
You can use custom where condition in your wordpress query as below.
Note: Use get_the_ID() instead of 215 in your case
//Add Filter
add_filter( 'posts_where' , 'posts_where_for_ID' );
function posts_where_for_ID( $where ) {
$where .= ' AND ID < '. 215;
return $where;
}
//Create args
$args = array(
'numberposts' => 5, //$wprpi_value['post']
'post__not_in' => array(215),
'orderby' => 'ID',
'order' => 'DESC',
'post_status' => 'publish',
'suppress_filters' => FALSE
);
//Get the posts
$desc_posts = get_posts($args);
//Store post ids
$p_ids = array();
foreach($desc_posts as $posts_) {
$p_ids[] = $posts_->ID;
}
//Your ids are here
var_dump($p_ids);
This will applied to all get_posts() query in which suppress_filters passed in args.
If you have custom post_type then ckeck for post type or if you have single page then add in that page only.

WordPress query arguments set order statically

I am trying to order my WordPress query by category ID but want to set the order statically.
below are the arguments that set the order:
'orderby' => 'ID',
'order' => 'ASC',
Is it possible to set the 'order' statically
like so:
'order' => '50,49,48,51',
I have tried using the post_in attribute but still am not seeing the order update:
$args = array(
'post_type' => $custom_post_type,
"$taxonomy" => $taxonomy_term->slug,
'post_status' => 'publish',
'post_in' => array(5,47,48,49,46,50),
'orderby' => 'post_in',
'posts_per_page' => 9999
);
function posts_orderby( $orderby ) {
global $wpdb;
$orderby = 'FIND_IN_SET(ID, "50,49,48,51")';
return $orderby;
}
add_filter('posts_orderby', 'posts_orderby');
Reading: Returning query results in predefined order
http://www.undolog.com/2012/03/13/wordpress-get_posts-e-orderby/
go for this plugin : "taxonomy-terms-order"
taxonomy-terms-order
thanks

Categories