get_categories() order by "term_order"? - php

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

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>");
}

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/

Ordering related products by ID (DESC) in WooCommerce

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

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.

Ordering Wordpress posts based on parent category

UPDATE: I have tried using the following code:
<?php if (is_category(events)) {
$posts = query_posts($query_string . '&orderby=event_date&order=desc');
} else {
$posts = query_posts($query_string . '&orderby=title&order=asc');
}
?>
Is there any reason why that wouldnt work? It seems to work fine organising posts in alphabetical order, but still no luck on the date order within 'events'.
--
After searching through various existing questions I can't quite find a solution to what I am trying to do.
Currently all posts on my site are ordered alphabetically, which is fine except for one new category that I have added. For this category I want to order all posts by a value that I enter into a custom field. The field is called 'event_date' - so I want to order the posts by date essentially, but not the date the post was created, the date the user manually enters into this field.
I managed to get it working by using:
<?php if (is_category($events)) { $posts = query_posts($query_string . '&orderby=$event_date&order=asc'); } ?>
However this overrides the aphabetical order for all other pages.
For alphabetical order I am using:
<?php if (is_category()) { $posts = query_posts( $query_string . '&orderby=title&order=asc' ); } ?>
Essentially I want a statement that tells the page to order all posts in aphabetical order, unless the category is 'events', where I want to order them by the custom event date.
As you can probably tell I'm very much front end, not back end so a lot of this is fairly new to me, so any help or advice is appreciated.
To order posts by a custom field value, you need add the custom meta field to the query itself. orderby=meta_value in addition to meta_key=metafieldid will allow ordering in this fashion.
I would use the pre_get_posts hook and modify the query object if get_query_var( "cat" ) (or a similar query var) returns the desired post category.
add_action( "pre_get_posts", "custom_event_post_order" );
function custom_event_post_order( $query )
{
$queried_category = $query -> get_query_var( "cat" );
/*
* If the query in question is the template's main query and
* the category ID matches. You can remove the "is_main_query()"
* check if you need to have every single query overridden on
* a page (e.g. secondary queries, internal queries, etc.).
*/
if ( $query -> is_main_query() && $queried_category == 123 )
{
$query -> set( "meta_key", "event_date" ); // Your custom field ID.
$query -> set( "orderby", "meta_value" ); // Or "meta_value_num".
$query -> set( "order", "ASC" ); // Or "DESC".
}
}
Remember that this approach overrides all queries that are using the category in question. You can build custom WP_Query objects that use their own parameters for constructing loops.
You also should standardize the way you save the custom field data to the database. For dates I prefer using UNIX-timestamp formatted times that are easy to move around and manipulate. This way no accidents happen when querying and some data is formatted in another way that the rest is.
Disclaimer: I did not have the time to test the above code in action, but the general idea should work properly.
EDIT: of course the above code should be inserted to functions.php or a similar generic functions file.
What about:
<?php $posts = query_posts($query_string . (is_category($events)?'&orderby='.$event_date:'&orderby=title') . '&order=asc'); ?>
<?php
$recent = new WP_Query(“cat=ID&showposts=x”);
while($recent->have_posts()) : $recent->the_post();
?>
Hopefully I understood your question, use the WP_Query and within the orderby add a space between your order by columns:
$args = array(
'posts_per_page' => 100,
'orderby' => 'title',
'order' => 'ASC',
);
if(is_category($events)){
$args['orderby'] .= " meta_value_num";
$args['meta_key'] = 'event_date';
}
$posts = (array) new WP_Query( $args );

Categories