Wordpress query with multiple meta meta keys - wordpress

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/
";

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

Mod a Wordpress Function to have 10 iteration per times

Im tryng to mod this function to make an update more powerful.
What im tryng to do is to mod this function:
add_action( 'wp_loaded', 'cron_revise_changed_listings' );
function cron_revise_changed_listings() {
global $wpdb;
if ( !isset( $_REQUEST['wplister_revise_all'] ) ) {
return;
}
$limit = isset( $_REQUEST['revise_limit'] ) ? intval( $_REQUEST['revise_limit'] ) : 10;
$listings = $wpdb->get_results("
SELECT id, account_id
FROM {$wpdb->prefix}ebay_auctions
WHERE status = 'changed'
ORDER BY id DESC
LIMIT {$limit}", ARRAY_A );
if ( empty( $listings ) ) {
die( json_encode( array( 'revised' => 0 ) ) );
}
$lm = new ListingsModel();
$revised = 0;
$last_account_id = false;
foreach ( $listings as $listing ) {
if ( $last_account_id != $listing['account_id'] ) {
$last_account_id = $listing['account_id'];
WPLE()->initEC( $listing['account_id'] );
}
$lm->reviseItem( $listing['id'], WPLE()->EC->session );
$revised++;
}
WPLE()->EC->closeEbay();
die( json_encode( array( 'revised' => $revised ) ) );
}
What i need to obtain is to repeat cycle for each, but with a step of 10 items per time so for revise 100 items it need only to do 10 cicles and not 100...someone have any ideas?

How to limit query in price filter

How to limit query to 6 in woocommerce product price filter short-code [products_by_price min="100" max="300"]? The code below is based on woocommerce product short-code which unfortunately does not support per_page. In this case I need to limit query to 6 to avoid showing all products.
add_shortcode( 'wc_products_price_range', 'wc_products_price_range' );
function wc_products_price_range( $atts, $content, $shortcode ) {
if ( class_exists( 'WooCommerce' ) ) {
$shortcodes = new WC_Shortcodes();
if ( is_array( $atts ) ) {
$min = (int) $atts['min'];
$max = (int) $atts['max'];
if ( $min && $max ) {
$and = "meta_value BETWEEN $min AND $max";
} else {
if ( $min ) {
$and = "meta_value >= $min";
} elseif ( $max ) {
$and = "meta_value <= $max";
}
}
if ( $and ) {
global $wpdb;
$query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and";
$ids = $wpdb->get_col( $query );
if ( ! empty( $ids ) ) {
$atts['ids'] = implode( ",", $ids );
}
}
}
return $shortcodes->products( $atts );
}
}
After a quick scan of WC shortcode class I have came across this :
public static function products( $atts ) {
$atts = shortcode_atts( array(
'columns' => '4',
'orderby' => 'title',
'order' => 'asc',
'ids' => '',
'skus' => ''
), $atts );
it means you can pass 'column' attribute along with ids where you can limit posts per page.
and in this query :
$query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and";
you can use limit 0,6 with order by clause.
Hope this helps.
OR
random rows:
SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;
or you can pass 'rand' to attributes in shortcode.

wordpress - Sortable custom fields columns

I added some custom fields (dates) in my admin columns. I try to make them sortable but in order to do that I need to convert them from string to date. My naive and simple code obviously doesn't work... Can someone point out my error(s) ?
add_action( 'pre_get_posts', 'orderby_date' );
function orderby_date( $query ) {
$orderby = $query->get( 'orderby');
if( 'start' == $orderby ) {
$query->set('meta_key','class_start');
$query->set('orderby',"STR_TO_DATE(meta_value,'%m/%d/%Y')");
}
}
This is what you are looking for:
add_filter( 'posts_clauses', 'manage_wp_posts_be_qe_posts_clauses', 1, 2 );
function manage_wp_posts_be_qe_posts_clauses( $pieces, $query ) {
global $wpdb;
if ( $query->is_main_query() && ( $orderby = $query->get( 'orderby' ) ) ) {
$order = strtoupper( $query->get( 'order' ) );
if ( ! in_array( $order, array( 'ASC', 'DESC' ) ) )
$order = 'ASC';
switch( $orderby ) {
case 'class_start':
$pieces[ 'join' ] .= " LEFT JOIN $wpdb->postmeta wp_rd ON wp_rd.post_id = {$wpdb->posts}.ID AND wp_rd.meta_key = 'class_start'";
$pieces[ 'orderby' ] = "STR_TO_DATE( wp_rd.meta_value,'%m/%d/%Y' ) $order, " . $pieces[ 'orderby' ];
break;
}
}
return $pieces;
}
You can read more about it here: http://wpdreamer.com/2014/04/how-to-make-your-wordpress-admin-columns-sortable/

Reduce and clean code

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

Resources