Ordering related products by ID (DESC) in WooCommerce - php

So here's the problem that i ran into. I'm trying to show new products in the related products tab on a WooCommerce Store (WP 4.9.6, WooCommerce 3.3.5), but no matter what i try it returns the very same results, ordering them according to the arguments i have in the array. What i can't seem to make it do, is change the way the query works because it seems to me that it always runs the same thing and gives me the same rows from the database ordered according to my arguments.
add_filter( 'woocommerce_output_related_products_args', function( $args )
{
$args = wp_parse_args( array('orderby' => 'date','order' => 'DESC','posts_per_page' => 4), $args );
return $args;
});

Related

How to get a Woocommerce order by meta_value in Wordpress

I am building a custom Wordpress plugin to integrate with Woocommerce Orders. This plugin receives a string as input. Upon receiving this string input, the plugin must search Woocommerce for an order that matches the passed in value. The Woocommerce Orders have a custom field my_number which stores the values I am searching. I read about WP_Query class. I read about get_posts function. Both takes a list of args as a parameter. All these do not answer my problem. The problem is that running queries using all these Wordpress built-in capabilities are not returning a result! What is fun to me is that if I use the same meta_key on a normal Wordpress post, I do get a result back. So, why am I not getting the same result back on a Wocommerce Order. You will see, I have tried even to remove post_type filter and all other fields and only left the meta_key. This is just one example:
$args = array(
'meta_key' => 'my_number',
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
return ("<pre>".print_r( $post,true)."</pre>");
}
So, my question is how to a search an Order in Woocomerce Wordpress using the existing functionalities.
I can see the record in MySQL when I run
SELECT * FROM `wordpressTable_postmeta` WHERE meta_key = 'my_number'
Attached screenshot shows this order, with the custom field.
Okay, so I came across this article. To query Woocommerce order, you need to use the Woocomerce class WC_Order_Query.
https://pluginrepublic.com/querying-woocommerce-orders/
Now my fixed query looks like this and it is returning something:
$args = array(
'meta_key' => 'my_number',
);
$query = new WC_Order_Query( $args );
$orders = $query->get_orders();
foreach ( $orders as $order ) {
return ("<pre>".print_r( $order,true)."</pre>");
}

Pulling shipping details from one wordpress plugin into another

I believe I am close but entirely unsure as my limited php knowledge is based on trial and error. I am trying to pull data from a plugin that creates my shipping label into a plugin that tracks shipping. Specifically Elex EasyPost into Advanced Shipping Tracking.
I have an example snippet for shipstation integration from AST here:
<?php
add_action( 'woocommerce_shipstation_shipnotify', 'add_tracking_information_into_order', 10, 2 );
function add_tracking_information_into_order($order, $tracking_details){
$order_id = $order->get_id();
$args = array(
'tracking_provider' => $tracking_details['carrier'],
'tracking_number' => wc_clean( $tracking_details['tracking_number'] ),
'date_shipped' => wc_clean( $tracking_details['ship_date'] ),
'status_shipped' => 1,
);
$ast = new WC_Advanced_Shipment_Tracking_Actions;
$tracking_item = $ast->insert_tracking_item( $order_id, $args );
}
It should be similar but obviously I need to replace the hook and the items in the array. Here is what Elex sent me when asked for the hooks they are using.
get_post_meta($order_id, ‘wf_easypost_labels’);
Sample output:
array(
0=>(‘url’=>label_url,’tracking_number’=> (string)’tracking code’,’integrator_txn_id’=> ‘integerator_id’,’shipment_id’=>’package_shipment_id’,’order_date’=>order_date,’carrier’=>EX:USPS,”link”=>tracking_link,);//First package
1=>(‘url’=>label_url,’tracking_number’=> (string)’tracking code’,’integrator_txn_id’=> ‘integerator_id’,’shipment_id’=>’package_shipment_id’,’order_date’=>order_date,’carrier’=>EX:USPS,”link”=>tracking_link,);//Second package
)
So here is my attempt to use their array in my own snippet:
<?php
add_action( 'woocommerce_checkout_update_order_meta', 'add_tracking_information_into_order', 10, 2 );
function add_tracking_information_into_order($order, $myship_func){
$myship_func = get_post_meta($order_id, 'wf_easypost_labels');
$order_id = $order->get_id();
$args = array(
'tracking_provider' => $myship_func['carrier'],
'tracking_number' => wc_clean($myship_func['tracking code']),
'date_shipped' => wc_clean($myship_func['order_date']),
'status_shipped' => 1,
);
$ast = new WC_Advanced_Shipment_Tracking_Actions;
$tracking_item = $ast->insert_tracking_item( $order_id, $args );
}
When the order is initially filled and the label is generated Elex grabs all the data from and sticks it in the meta. I need to pull that meta either at the time of generation or post generation and stick it in the AST fields.
My main question is thus - Am I on the right track here? Do I just need to figure out the correct hook or is my method for accessing the Elex array incorrect? Again, I usually compare codes, slice and dice, and get things to "look right" and then they work (or not). I myself don't have too deep of knowledge about arrays or class functions (which I believe the Elex one is).
In this case the code is silently failing so I suspect it is the hook involved or a combination of the hook and my code.

How to exclude category from homepage by using php function rather than default WP function?

I bought a WordPress theme for affiliate marketing business. I have 1000+ stores on my website and hence hundred of coupons on homepage.I simply write a short-code to fetch all coupons and they started to appear on homepage .All coupons are based on different categories.
How can i exclude a number of coupons from homepage and that is possible only if we can exclude some categories from homepage based on their IDs.
I Google it many times but each time i found "pre_get_posts" function to do so. But in my case, it's not working at all. The code is below
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-5' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
Through this code i am trying to exclude desired categories. I also tried to modified above code in different ways but none of my solution/idea worked.
What i think is the reason behind why above code is no working is the function only works for default "Category" option under "Posts"on Dashboard. And my categories are coming from another option on Dashboard that's "Coupons" -> "Offer Categories".
See screenshot: Offer Categories
May be or may be not, i need to modify the above function in a way that it can select my expected categories. But as i have lack of knowledge in PHP so i don't know what and how to do?
I'm badly stuck here and hoping to get some help from experts.
Thanks in advance
Try this code.
if(is_home() || is_front_page()){
$args_active_coupons['tax_query'][] = array(
'taxonomy' => 'offer_categories',
'field' => 'id',
'terms' => array(214),
'operator' => 'NOT IN',
);
}
If you want to hard code all the excluded category, you have to put your category ID with (-) prefix. e.g
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-<CAT_ID>, -<CAT_ID>, -<CAT_ID>' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
Here: CAT_ID should be excluded category id.
In another way, you could use a plugin:
https://wordpress.org/plugins/ultimate-category-excluder/

exclude category from wordpress if not required

I'm having a bad time trying to make wordpress querys excluding categories unless asked.
I mean, if not specifically asked (ex: $args= array('cat'=>'-35')) , the loop excludes this category.
what I got so far:
function exclude_categories( $wp_query ) {
$excluded_cats = array( '-35' , '-36' );
set_query_var( 'category__not_in', $excluded );
}
add_action( 'pre_get_posts', 'exclude_categories' );
This is doing ok excluding posts with this category but then if I try to ask for posts with this category it wont display any.
Any sugestions?
Can you show the whole code with when you ask for posts including this category?
Basically, you can set these parameters to inlucde or exclude categories in the query.
'category__not_in'=> array(1,2),
'category__in' => array(3,3)
However in your example you have already pre-set set_query_var( 'category__not_in', $excluded );
categories so even if you use category__in the query won't use it because of the usage of category__not_in. You need to set this parameter to empty value.

get_categories() order by "term_order"?

According to the WordPress codex, the get_categories() method accepts the following arguments for its orderby property:
**orderby** (string) Sort categories alphabetically or by unique category ID. The default is sort by Category ID. Valid values:
id
name - default
slug
count
term_group
However, taking a look into the "wp_term_relationships" table there is a seemingly unused field called "term_order" which, for every category I've ever created is set to 0.
Is it possible to use the term_order field in order to serve as an indexed sort order for categories?
I've placed incremental values into this field for my categories and I'm trying to pass the order to the function with the code below to no avail:
$cat_args=array(
'hierarchical' => 0,
'orderby' => 'term_order',
);
$categories = get_categories($cat_args);
Many years later,
You can add this code in your functions.php :
function wpcf_filter_terms_order( $orderby, $query_vars, $taxonomies ) {
return $query_vars['orderby'] == 'term_order' ? 'term_order' : $orderby;
}
add_filter( 'get_terms_orderby', 'wpcf_filter_terms_order', 10, 3 );
This code force WP to use the orderby => term_order argument in your term query.
The answer by #cédric-dagherir-dahive which suggests using get_terms_orderby filter is a great approach to display terms in the order they were added to the object (post). However, it does not work for all terms queries, and would generate the following error:
Unknown column 'term_order' in 'order clause'.
Because simply, some terms queries are only fetching data from (wp_terms & wp_term_taxonomy) database tables, and do not have any INNER JOIN with (wp_term_relationships) table, which has the term_order field. Hence the error message.
The order by term_order clause should only be added if the query is concerned about the many-to-many relationship between the taxonomy and the object (e.g. get_the_terms).
Therefore, I updated the code to firstly check if the term query involves objects before adding the term_order to the order clause:
function wpcf_filter_terms_order( $orderby, $query_vars, $taxonomies ) {
return ( ! is_null($query_vars["object_ids"]) ) ? 'term_order' : $orderby;
}
add_filter( 'get_terms_orderby', 'wpcf_filter_terms_order', 10, 3 );
I've searched all the wordpress functions and the only one you can use with 'term_order' is wp_get_object_terms and you can see its function here.From this point on, even if wordpress doesn't use this to filter the categories in get_categories() you or other theme/plugin developers can use the above function to get object_terms and to order/filter them by term_order.
A few more years later I found this solution:
The task can be solved with a filter and an adapted taxonomy.
https://core.trac.wordpress.org/ticket/5857#comment:4

Categories