Reduce and clean code - wordpress

In wordpress category.php I have this code:
if ( is_category('cat-1') ) {
$the_query = new WP_Query( array ( 'post_type' => 'mueble', 'category_name' => 'cat-1' , 'posts_per_page' => 3 ) ) ;
}
if ( is_category('cat-2') ) {
$the_query = new WP_Query( array ( 'post_type' => 'mueble', 'category_name' => 'cat-2' , 'posts_per_page' => 3 ) ) ;
}
if ( is_category('cat-3') ) {
$the_query = new WP_Query( array ( 'post_type' => 'mueble', 'category_name' => 'cat-3' , 'posts_per_page' => 3 ) ) ;
}
while ( $the_query->have_posts() ) : $the_query->the_post();
...
endwhile; wp_reset_postdata();
How can I simplify the code? I have 30 categories and too many conditionals isn't ideal...

if you know the exact number of categories, you can try a for loop:
for ($x=0; $x<=30; $x++) {
if ( is_category('cat-' . $x) ) { $the_query = new WP_Query( array ( 'post_type' => 'mueble', 'category_name' => 'cat-' . $x , 'posts_per_page' => 3 ) ) ; }
}

Related

WooCommerce | Customer's total spend on completed orders in a given time period

The code below is said to give the total spent spent over 30 days (if I'm not mistaken). But in my test, it calculates for the current month. How can I not update this code for last 6 months(180 days). The important thing is to be able to easily change the coverage day and make the calculation for the completed orders. Thanks.
Code resource:https://github.com/anaymark/woocommerce-monthly-spent-by-user/blob/master/total-spent-month-by-user.php
function total_spent_for_user_30days( $user_id=null ) {
if ( empty($user_id) ){
$user_id = get_current_user_id();
}
$today_year = date( 'Y' );
$today_month = date( 'm' );
$day = date( 'd' );
if ($today_month == '01') {
$month = '12';
$year = $today_year - 1;
} else{
$month = $today_month - 1;
$month = sprintf("%02d", $month);
$year = $today_year - 1;
}
// ORDERS FOR LAST 30 DAYS (Time calculations)
$now = strtotime('now');
$gap_days = 30;
$gap_days_in_seconds = 60*60*24*$gap_days;
$gap_time = $now - $gap_days_in_seconds;
$args = array(
'post_type' => 'shop_order',
'post_status' => array( 'wc-completed' ),
// all posts
'numberposts' => -1,
// for current user id
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'date_query' => array(
//orders published on last 30 days
'relation' => 'OR',
array(
'year' => $today_year,
'month' => $today_month,
),
array(
'year' => $year,
'month' => $month,
),
),
);
// GET ALL ORDERS
$customer_orders = get_posts( $args );
$count = 0;
$total = 0;
$no_orders_message = __('No orders this month.', 'mytheme');
if (!empty($customer_orders)) {
$customer_orders_date = array();
foreach ( $customer_orders as $customer_order ){
$customer_order_date = strtotime($customer_order->post_date);
// PAST 30 DAYS
if ( $customer_order_date > $gap_time ) {
$customer_order_date;
$order = new WC_Order( $customer_order->ID );
$order_items = $order->get_items();
$total += $order->get_total();
// Going through each current customer items in the order
foreach ( $order_items as $order_item ){
$count++;
}
}
}
$monthly_spent_by_user = floatval( preg_replace( '#[^\d.]#', '', $total, $count ) );
return $monthly_spent_by_user;
} else {
return $no_orders_message;
}
}
add_shortcode( 'spent-last-month', 'total_spent_for_user_30days' );

query WooCommerce orders within a date range through a custom meta key

I have a meta_key called delivered_date, in date format, example 2021-05-13 16:01:26.
If I MUST use wc_get_orders( $args ), how can I get all orders within a date range?
Tried using the meta_compare argument but it returns nothing:
// The 2 variables below will come from a datepicker widget
$start_date = "2021-05-10 0:00:00";
$end_date = "2021-05-30 11:59:59";
$args = array(
'type' => 'shop_order',
'limit' => 100,
'paginate' => true,
'page' => 1,
'orderby' => 'id',
'order' => 'DESC',
'meta_key' => 'delivered_date',
'meta_value' => array($start_date, $end_date),
'meta_compare' => 'BETWEEN',
);
$result = wc_get_orders( $args );
You are close, use date — Format a local time/date
So you get:
// The 2 variables below will come from a datepicker widget
$start_date = date( '2021-05-10 00:00:00' );
$end_date = date( '2021-05-30 11:59:59' );
$args = array(
'orderby' => 'id',
'order' => 'DESC',
'meta_key' => 'delivered_date',
'meta_value' => array( $start_date, $end_date ),
'meta_compare' => 'BETWEEN',
);
$orders = wc_get_orders( $args );
// NOT empty
if ( ! empty ( $orders ) ) {
foreach ( $orders as $order ) {
echo '<p>ID = ' . $order->get_id() . '</p>';
}
}
Result: ID = 2525, ID = 2524, ID = 2523

Group results if meta_value is the same

I would like to group the results of my query if the meta_value is the same for any results. I would expect an output like this:
Group 1
- 1111
- 1111
- 1111
Group 2
- 1234
- 1234
Here is my query:
$args = array(
'post_type' => 'product-api',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'last_updated',
'value' => '',
'compare' => '!=',
)
),
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$count++;
$the_query->the_post();
$model = get_post_meta(get_the_id(), 'product_model', true);
echo $model;
}
}
wp_reset_postdata();
What would be the best approach to achieve this?

WP_Query returns nothing

I'm trying to make a function
that adds a shortcode which replace the shortcode into the list of attached files with pagination.
The problem is, WP_Query() doesn't return anything.
The functions's code is below.
It's in my functions.php, and It will be called in my content-page.php.
$a = shortcode_atts( array( 'number' => '10'), $atts );
//Protect against arbitrary paged values
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array(
'post_type' => 'attachment',
'post_parent' => get_the_ID(),
'posts_per_page' => $a['number'],
'paged' => $paged
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
the_title();
endwhile;
$big = 999999999; // need an unlikely integer
$retuen_string .= paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $the_query->max_num_pages
) );
wp_reset_postdata();
else :
_e( 'Sorry, no posts matched your criteria.' );
endif;
And print_r($the_query) result is below.
WP_Query Object (
[query_vars] => Array (
[post_type] => attachment
[post_parent] => 26
[posts_per_page] => 15
[paged] => 1
[error] =>
[m] =>
[p] => 0
[subpost] =>
[subpost_id] =>
[attachment] =>
[attachment_id] => 0
[name] =>
[static] =>
[pagename] =>
[page_id] => 0
[second] =>
[minute] =>
[hour] =>
[day] => 0
[monthnum] => 0
[year] => 0
[w] => 0
[category_name] =>
[tag] =>
[cat] =>
[tag_id] =>
[author] =>
[author_name] =>
[feed] =>
[tb] =>
[comments_popup] =>
[meta_key] =>
[meta_value] =>
[preview] =>
[s] =>
[sentence] =>
[fields] =>
[menu_order] =>
[category__in] => Array ( )
[category__not_in] => Array ( )
[category__and] => Array ( )
[post__in] => Array ( )
[post__not_in] => Array ( )
[tag__in] => Array ( )
[tag__not_in] => Array ( )
[tag__and] => Array ( )
[tag_slug__in] => Array ( )
[tag_slug__and] => Array ( )
[post_parent__in] => Array ( )
[post_parent__not_in] => Array ( )
[author__in] => Array ( )
[author__not_in] => Array ( )
[ignore_sticky_posts] =>
[suppress_filters] =>
[cache_results] => 1
[update_post_term_cache] => 1
[update_post_meta_cache] => 1
[nopaging] =>
[comments_per_page] => 50
[no_found_rows] =>
[order] => DESC
)
[tax_query] => WP_Tax_Query Object (
[queries] => Array ( )
[relation] => AND
)
[meta_query] => WP_Meta_Query Object (
[queries] => Array ( )
[relation] =>
)
[date_query] =>
[post_count] => 0
[current_post] => -1
[in_the_loop] =>
[comment_count] => 0
[current_comment] => -1
[found_posts] => 0
[max_num_pages] => 0
[max_num_comment_pages] => 0
[is_single] => [is_preview] =>
[is_page] =>
[is_archive] =>
[is_date] =>
[is_year] =>
[is_month] =>
[is_day] =>
[is_time] =>
[is_author] =>
[is_category] =>
[is_tag] =>
[is_tax] =>
[is_search] =>
[is_feed] =>
[is_comment_feed] =>
[is_trackback] =>
[is_home] => 1
[is_404] =>
[is_comments_popup] =>
[is_paged] =>
[is_admin] =>
[is_attachment] =>
[is_singular] =>
[is_robots] =>
[is_posts_page] =>
[is_post_type_archive] =>
[query_vars_hash] => ab31e2fb8fd323e014706374fb98b349
[query_vars_changed] =>
[thumbnails_cached] =>
[stopwords:WP_Query:private] =>
[query] => Array (
[post_type] => attachment
[post_parent] => 26
[posts_per_page] => 15
[paged] => 1
)
[request] => SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_parent = 26 AND wp_posts.post_type = 'attachment' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 15
[posts] => Array ( )
)
Can anyone help, please?
$a = shortcode_atts( array( 'number' => '10'), $atts );
//Protect against arbitrary paged values
$temp = $the_query;
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'attachment',
'post_parent' => get_the_ID(),
'posts_per_page'=>'15',
'paged' => $paged
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
the_title();
endwhile;
$big = 999999999; // need an unlikely integer
$retuen_string .= paginate_links( array(
'base' => #add_query_arg('paged','%#%'),
'format' => '?paged=%#%',
'current' => $paged,
'total' => $the_query->max_num_pages
));
wp_reset_postdata();
$the_query = null;
$the_query = $temp;
else :
_e( 'Sorry, no posts matched your criteria.' );
endif;
I found the solution.
Had to add 'post_status' => 'inherit' in the $args.
Like this.
$args = array(
'post_type' => 'attachment',
'post_parent' => get_the_ID(),
'posts_per_page'=>'15',
'paged' => $paged,
'post_status' => 'inherit'
);
OMG. so simple.
The code was nothing wrong.
I just passed the wrong arguments...

Wordpress query with multiple meta meta keys

Can someone tell me what wrong with this query.
if ( isset( $_GET['lokacija'] ) && !empty( $_GET['lokacija'] ) ) {
$lokacija = $_GET['lokacija'];
} else { $lokacija = ''; }
if ( isset( $_GET['tip'] ) && !empty( $_GET['tip'] ) ) {
$tip = $_GET['tip'];
} else { $tip = ''; }
if ( isset( $_GET['sobe'] ) && !empty( $_GET['sobe'] ) ) {
$sobe = $_GET['sobe'];
} else { $sobe = ''; }
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args2 = array(
'posts_per_page' => 10,
'post_type' => 'nekretnine',
'paged' => $paged,
if ($lokacija != '') {
'meta_query' => array(
array (
'key' => 'lokacija',
'value' => $lokacija.''
),
)
}
);
$wp_query = new WP_Query( $args2 );
This code gives me error
Parse error: syntax error, unexpected T_IF, expecting ')' in
*/wp-content/themes/gs/page-nek-pretraga.php on line 23;
Line 23 is line that starts with if ($lokacija)...
What i want to do is to use multiple meta_query that i can get from php get (www.blabla./com/page1/?lokacija=foo&tip=foo&sobe=3)
But, i want it only if lets say $lokacija is not empty. Same for other two (possible 5-6 later) fields.
You can not include if condition in array. Whatever you are trying to achieve with above code is you can achieve with this following code.
$args2 = array(
'posts_per_page' => 10,
'post_type' => 'nekretnine',
'paged' => $paged,
);
if ($lokacija != '') {
$args2['meta_query'] = array(
array (
'key' => 'lokacija',
'value' => $lokacija.''
),
);
}
To check for multiple custom fields we have to join the meta table twice.
So the copy of the table is joined with a different temporary table name.
global $wpdb; $query = " SELECT * FROM {$wpdb--->prefix}posts
INNER JOIN {$wpdb->prefix}postmeta m1
ON ( {$wpdb->prefix}posts.ID = m1.post_id )
INNER JOIN {$wpdb->prefix}postmeta m2
ON ( {$wpdb->prefix}posts.ID = m2.post_id )
WHERE
{$wpdb->prefix}posts.post_type = 'post'
AND {$wpdb->prefix}posts.post_status = 'publish'
AND ( m1.meta_key = 'date' AND m1.meta_value > '2010-12-05 00:00:00' )
AND ( m1.meta_key = 'date' AND m1.meta_value < '2010-12-12 00:00:00' ) AND ( m2.meta_key = 'some_other_meta_value' AND m2.meta_value != '' ) GROUP BY {$wpdb->prefix}posts.ID
ORDER BY {$wpdb->prefix}posts.post_date
DESC;
For More Details Visit : http://realtuts.com/write-custom-wordpress-sql-query-multiple-meta-values/
";

Resources