I have a custom post type of products, and each product belongs to a product category. I am trying to query the products to get all products sorted alphabetically by their product category i.e. First: Product: Lion
Category: Animals
Last:
Product: Snowmobile
Category: Winter
I am using a custom field for the product category, but my query doesn't sort them alphabetically - but instead by which date they are published. The product_cat_meta field is a regular text field set up in custom fields. Query is here:
function get_products()
{
$args = array(
'post_type' => 'products',
'post_status' => 'publish',
'meta_key' => 'product_cat_meta',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => -1
);
$products = new WP_Query($args);
if ($products->have_posts()) {
$index = 0;
while ($products->have_posts()) {
$products->the_post();
$prod_meta = get_field('product_cat_meta');
echo $prod_meta;
);
$index++;
} // end while
} // end if
}
The result of this query just returns the prod category in the way they are set up in wordpress – the latest posts first, but not sorted alphabetically
You can try to put the code in functions.php file.
The code, which can be dropped into your current theme’s functions.php if you like:
function get_products()
{
$args = array(
'post_type' => 'products',
'post_status' => 'publish',
'meta_key' => 'product_cat_meta',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1
);
$products = new WP_Query($args);
if ($products->have_posts()) {
$index = 0;
while ($products->have_posts()) {
$products->the_post();
$prod_meta = get_field('product_cat_meta');
echo $prod_meta;
);
$index++;
} // end while
} // end if
}
Get More details, follow the link: https://codex.wordpress.org/Alphabetizing_Posts
Related
My meta_query is ordering just by ID, but I need order by the post_title
Heres the query I'm using
<?php
$args = array(
'orderby' => 'meta_value', // Or post by custom field
'order' => 'DESC', // Or post by custom field
'meta_key' => 'case-solucao',
'post_type' => 'testemunho', // Just the post type
'posts_per_page' => -1, // Show all available post
);
query_posts($args);
while(have_posts()){
the_post();
$solucoesCases = get_field('case-solucao');
foreach ($solucoesCases as $solCase) {
// echo count($solCase->ID);
}
echo $solCase->ID ." - ". $solCase->post_title."\n";
}
?>
I have a Custon Field that's link the solution to post_type. But Its only sort by ID, and I need to sort by Post_title.
I'm really lost. Hope someone could help me.
Try this. If, I'm correct, you need to display the title along the your custom field.
$args = array(
'orderby' => 'title', // This will order the post by title
'post_type' => 'testemunho', // Just the post type
'posts_per_page' => -1, // Show all available post
);
query_posts($args);
while(have_posts()){
the_post();
foreach ($solucoesCases as $solCase) {
$solucoesCases = get_field('case-solucao', $solCase->ID ); // add the ID of the post_type
echo $solCase->ID ." - ". $solCase->post_title."\n"; // will print all the title
echo $solucoesCases;
}
}
I'm building a woocommerce website using storefront.
On each category page, I wish to display product ordered by tag.
Each product has only one tag.
TAG 1
product a
product b
TAG 2
product x
product y
I think I can retrieve all the data I need from the DB.
But I have no clue how to use them to display my products ordered by tags.
EDITED
// GET CATEGORY ID
$currentCategory = get_queried_object();
$catSlug = $currentCategory->slug;
// GET PRODCUTS FROM CURRENT CATEGORY
$args = array(
'post_type' => 'product',
'product_cat' => $catSlug,
'orderby' => 'rand'
);
$prodLoop = new WP_Query( $args );
while ( $prodLoop->have_posts() ){
$prodLoop->the_post();
global $product;
echo the_title();
echo the_ID();
echo '</br>';
}
// GET TAGS ID
$tag_args = array(
'taxonomy' => 'product_tag',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
);
$tag_query = new WP_Term_Query($tag_args);
foreach($tag_query->get_terms() as $term){
print_r($term->term_id);
}
//GET ALL PRODUCTS ID
$prod_args = new WC_Product_Query( array(
'limit' => 5,
'order' => 'ASC',
'return' => 'ids',
));
$products = $prod_args->get_products();
foreach($products as $prod){
print_r($prod);
}
I read many things, maybe I could you a SELECT xxx query, something like a one to many realtionship query, or an usort function, but I don't know where to do... I tried many things, but by now all I got is a headache and feeling hopeless...
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']);
}
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();
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();