I'm making an API using WP-JSON for a client, they're using a plugin that manage events and the API should return next events, not the past.
function app_get_newer_posts($data) {
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
'posts_per_page' => 99,
'paged' => $data['page'],
'meta_key' => 'ovaem_date_start_time',
'orderby' => 'meta_value_num',
'order' => 'asc'
);
$query = new WP_Query( $args );
if ($query->have_posts()) {
$ret = [];
while ( $query->have_posts() ) {
$term = get_term(get_the_ID,'');
$query->the_post();
setlocale(LC_TIME, 'it_IT.UTF8', 'it.UTF8', 'it_IT.UTF-8', 'it.UTF-8');
if(get_post_meta(get_the_ID(), 'ovaem_date_start_time')[0] < date("Y-m-d")) {
$ret['schedule'][] = [
'date' => strftime('%e %B %Y',get_post_meta(get_the_ID(), 'ovaem_date_start_time')[0]),
'category' => [ get_the_terms( get_the_ID(), 'categorie' )[0]->name ],
'premium' => false,
'url' => get_the_permalink(),
'groups' => [[
'time' => utf8_encode( strftime("%d %b %Y", get_post_meta(get_the_ID(), 'ovaem_date_start_time')[0]) ),
'sessions' => [[
'id' => get_the_ID(),
'name' => html_entity_decode(the_title('','',false), ENT_QUOTES),
'location' => get_the_terms( get_the_ID(), 'location')[0]->name,
'description' => get_the_content(),
'timeStart' => date('d M Y h:i',get_post_meta(get_the_ID(), 'ovaem_date_start_time')[0]),
'timeEnd' => date('d M Y h:i',get_post_meta(get_the_ID(), 'ovaem_date_end_time')[0]),
'categories' => [ get_the_terms( get_the_ID(), 'categorie' )[0]->name ],
'pic' => get_the_post_thumbnail_url(),
'position' => [
'lat' => get_post_meta(get_the_ID(), 'ovaem_event_map_lat')[0],
'lng' => get_post_meta(get_the_ID(), 'ovaem_event_map_lng')[0]],
'slug' => get_post_field( 'post_name', get_post() ),
]]
]]
];
}
}
} else {
$ret = "-1";
}
return $ret;
}
At the moment, it get all the posts of type event and order by meta_key "ovaem_date_start_time", but it should exclude all the past events.
What parameter should I pass to the args array to compare current meta_key value to today date?
'meta_query' => array(
array(
'key' => 'ovaem_date_start_time',
'value' => time(),
'compare' => '>=',
)
)
Would something like this work, getting all events where the start date is greater than the current date, you may need to change the value as it depends what ovaem_date_start_time is actually saved as whether its time or datetime
Related
I want to get a list of products with sku and post id with this code, everything seems fine and ok with this code :
$statuses = array('publish', 'draft');
// Args on the main query for WC_Product_Query
$args = [
'status' => $statuses,
'orderby' => 'name',
'order' => 'ASC',
'limit' => -1,
];
$vendor_products = wc_get_products($args);
$list_array = array();
foreach ($vendor_products as $key => $product) {
if ($product->get_type() == "variable") {
// Args on product variations query for a variable product using a WP_Query
$args2 = array(
'post_parent' => $product->get_id(),
'post_type' => 'product_variation',
'orderby' => array( 'menu_order' => 'ASC', 'ID' => 'ASC' ),
'fields' => 'ids',
'numberposts' => -1,
);
foreach ( get_posts( $args2 ) as $child_id ) {
// get an instance of the WC_Variation_product Object
$variation = wc_get_product( $child_id );
if ( ! $variation || ! $variation->exists() ) {
continue;
}
$list_array[] = array(
'sku' => $variation->get_sku(),
'postid' => $variation->get_id()
);
}
} else {
$list_array[] = array(
'sku' => $product->get_sku(),
'postid' => $product->get_id()
);
}
}
I have total 1660 (470 published and 1,190 drafted) products but it's just returns 501 products and i don't know why!
this is my products in woocommerce:
this is the final result of query :
this is the result of Janki's code
// Woocommerce get all products
$args = array(
'post_type' => array('product','product_variation'),
'meta_key' => '_sku',
'post_status' => array('publish','draft'),
'meta_query' => array(
array(
'key' => '_sku',
'compare' => 'EXISTS',
),
),
);
$products = new WP_Query($args);
/* using this code you can get all products */
/* this may help you to get details */
I view the other post but I found nothing, I'm on since 3 days :
I want display 3 'evenements' in the order ASC
but 2018 is always before 2017
$auj = date('Ymd');
$queryEvent = new WP_Query(
array(
'category_name' => 'evenements',
'posts_per_page' => 3,
'meta_key' => 'date_de_fin',
'orberby' => 'meta_key',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'date_de_fin',
'value' => $auj,
'compare' => '>=',
),
)
)
);
?>
someone has an idea ?
I have updated your code .Please try your updated query.
<?php $auj = date('Ymd');
$queryEvent = new WP_Query(
array(
'category_name' => 'evenements',
'posts_per_page' => 3,
'meta_key' => 'date_de_fin',
'orberby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'date_de_fin',
'value' => $auj,
'compare' => '>=',
'type' => 'DATE'
),
)
));
?>
I have replace 'orderby' value & added 'type' parameter in meta_query.
Hope, this may be helpful to you.
As your date format is not in Y-m-d so you need to define your own
logic for shorting
function wh_posts_orderby($orderby, $query) {
//Only for custom orderby key
if ($query->get('orderby') != 'yyyymmdd_date_format')
return $orderby;
if (!( $order = $query->get('order') ))
$order = 'ASC';
global $wpdb;
$fieldName = $wpdb->postmeta . '.meta_value';
return "STR_TO_DATE(" . $fieldName . ", '%Y%m%d') " . $order;
}
add_filter('posts_orderby', 'wh_posts_orderby', 10, 2);
Add the ^^above code to your active theme functions.php file.
Now you can sort your post by date (format YYYYMMDD)
$auj = date('Ymd');
$args = [
'category_name' => 'evenements',
'posts_per_page' => 3,
'meta_key' => 'date_de_fin',
'orberby' => 'yyyymmdd_date_format', //check this line
'order' => 'ASC',
'meta_query' => [
'relation' => 'AND', //added this
[
'key' => 'date_de_fin',
'value' => $auj,
'compare' => '>=',
'type' => 'DATE'
],
]
];
$queryEvent = new WP_Query($args);
if ($queryEvent->have_posts()) :
/* Start the Loop */
while ($queryEvent->have_posts()) : $queryEvent->the_post();
//you post
endwhile;
endif;
Related answer How do I query posts and use the 'orderby' attribute to order posts in loop according to date 'meta_value'?
Hope this helps!
I resolve by problem with a SQL query :
$queryEvent = $wpdb->get_results( 'SELECT * FROM cci_posts INNER JOIN cci_postmeta ON cci_posts.id = cci_postmeta.post_id INNER JOIN cci_term_relationships ON cci_posts.id = cci_term_relationships.object_id WHERE cci_term_relationships.term_taxonomy_id = 4 AND cci_postmeta.meta_key = "date_de_fin" AND cci_postmeta.meta_value > 20170221 AND cci_posts.post_status = "publish" ORDER BY cci_postmeta.meta_value ASC LIMIT 3', OBJECT );
//$queryEvent = new WP_Query($args);
?>
<?php if ( $queryEvent ) : ?>
<?php /* Start the Loop */ ?>
<?php foreach ($queryEvent as $post) {
setup_postdata($post); ?>
I have a shortcode which is working fine if iI put the single value for "rank" in shortcode.
[coaches_list category="dummy" number="3" rank="2"]
But I want to pass multiple values in "rank" as [coaches_list category="dummy" number="3" rank="2", "6"].
'rank' is a numeric type custom field associated with post.
I have searched alot on internet from last 2 days but found no result. Please let me know where I am having mistake.
Here is the piece of shortcode I bulit:
$args = array(
'number' => '-1',
'orderby' => 'id',
'order' => 'desc',
'category' => '',
'meta_key' => '',
'rank' => '',
), $atts )
);
global $post;
$html = "";
$my_query = new WP_Query( array('post_type' => 'post',
'posts_per_page' => $number, 'orderby' => $orderby, 'order' => $order, 'category' =>$category, 'meta_key' => 'rank', 'meta_value' => $rank ));
if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
I'd go for [coaches_list category="dummy" number="3" rank="2,6"]
And then you could make an array $ranks = explode(',',$rank);.
function my_shortcode($atts){
extract(shortcode_atts( $args = array(
'number' => '-1',
'orderby' => 'id',
'order' => 'desc',
'category' => '',
'meta_key' => '',
'rank' => '',
),$atts));
$ranks = explode(',',$rank);
$html = '<ul>';
$my_posts = get_posts(array(
'post_type' => 'post',
'posts_per_page' => $number,
'orderby' => $orderby,
'order' => $order,
'category' =>$category,
'meta_query' => array(
'key'=>'rank',
'value'=>$ranks,
'compare'=>'IN'
)
));
foreach($my_posts as $rankpost){
$html .= '<li>'.$rankpost->ID.': '.get_the_title($rankpost->ID).' - Rank: '.get_post_meta($rankpost->ID,'rank',true).'</li>';
}
$html .= '</ul>';
return $html;
}
Or maybe you could create a query that gives out all post with rank=2 AND/OR rank=6.
I have a custom content type (event), within that type I have a custom date field, with the name: 'date'. In my template I am running the WP_Query to return a list of events. I would like to only get events that are in the future (according to my custom 'date' field) and then order the list by that same field.
I have tried the following but it simply returns a list of all the 'events' in the system, regardless of date
$today = date('d M, y');
$args = array (
'post_type' => 'event',
'meta_query' => array(
array(
'key' => 'date',
'value' => $today,
'compare' => '>',
'type' => 'CHAR',
),
),
'meta_key' => 'date',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
As a note: if I replace the type from 'CHAR' to 'DATE' I get no results returned...
Try this:
functions.php
function custom_unixtimesamp ( $post_id ) {
if ( get_post_type( $post_id ) == 'events' ) {
$startdate = get_post_meta($post_id, 'event_date_begins', true);
if($startdate) {
$dateparts = explode('/', $startdate);
$newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
update_post_meta($post_id, 'unixstartdate', $newdate1 );
}
}
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);
then query
$today = time();
$args = array(
'post_type' => 'events',
'post_status' => 'publish',
'posts_per_page' => '10',
'meta_query' => array(
array(
'key' => 'unixstartdate',
'compare' => '>=',
'value' => $today,
)
),
'meta_key' => 'event_date_begins',
'orderby' => 'meta_value',
'order' => 'ASC',
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ),
);
For those familiar with the ACF plugin...
I have some events posts that are currently displaying in post order (see code below). I would like them to display in the order specified by the date-picker.
Can anyone tell me what to amend in the following - I have tried the documentation on the site, but my PHP is basic.
It says I need to add
'orderby' => 'meta_value_num',
But no joy.
<?php function le_whatson_aside() {
//THis loop is for the CPT
$args = array(
'post_type' => 'events', // enter your custom post type
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page'=> '10', // overrides posts per page in theme settings
'tax_query' => array(
array(
'taxonomy' => 'audience', //name of custom taxonomy
'field' => 'slug',
'terms' => 'everyone' //name of category
)
)
);
$loop = new WP_Query( $args );
if( $loop->have_posts() ):
?>
<div>
<h2>What's On</h2>
</div>
<div class="whatson entry-content">
<?php
while( $loop->have_posts() ): $loop->the_post(); global $post;
?>
<p class="whatson-date"><?php echo date("dS F Y",strtotime(get_field('date')));?></p>
<h4 class="whatson-title"><?php echo get_the_title(); ?></h4>
<?php
endwhile;
?>
</div>
<?php
endif; }
Thanks all.
Try
orderby=date or `post_date`
If not the easiest way is to save your custom field 'startdate' as a unix timestamp. To do this, add the following to your theme's functions.php
// CREATE UNIX TIME STAMP FROM DATE PICKER
function custom_unixtimesamp ( $post_id ) {
if ( get_post_type( $post_id ) == 'events' ) {
$startdate = get_post_meta($post_id, 'startdate', true);
if($startdate) {
$dateparts = explode('/', $startdate);
$newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
update_post_meta($post_id, 'unixstartdate', $newdate1 );
}
}
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);
The do:
$today = time();
$args = array(
'post_type' => 'events',
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => 'unixstartdate',
'compare' => '>=',
'value' => $today,
)
),
'meta_key' => 'startdate',
'orderby' => 'meta_value',
'order' => 'ASC',
);
$query = new WP_Query( $args );
$events = $query->posts;
Got it from here
I spent hours looking for this and I can confirm it works. See my code below.
If you're trying for a loop on a page with other loops, with a bunch of template parts in there, and you would also like to sort by a category, it goes :
$today = time();
$the_query = new WP_Query( array(
'post_type' => 'events',
'posts_per_page' => 3,
'meta_query' => array(
array(
'key' => 'start',
'value' => $today,
'compare' => '>=',
)
),
'tax_query' => array(
array (
'taxonomy' => 'the_taxonomy',
'field' => 'slug',
'terms' => 'the-name'
)
),
'meta_key' => 'start',
'orderby' => 'meta_value',
'order' => 'ASC',
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
get_template_part( 'content-events' );
endwhile;
wp_reset_postdata();
Of course, you have to include Unix the function beforehand.
function custom_unixtimesamp ( $post_id ) {
if ( get_post_type( $post_id ) == 'events' ) {
$startdate = get_post_meta($post_id, 'start', true);
if($startdate) {
$dateparts = explode('_', $startdate);
$newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
update_post_meta($post_id, 'unixstartdate', $newdate1 );
}
}
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);
I would approach it like this. Create a "named" meta query and then order by that query. The meta query uses "EXITS" to filter out posts that don't have a date set. This works with the ACF date picker when the dates are saved to the database using the default format d/m/Y. This approach also works with the datetime picker.
$query = new WP_Query([
"meta_query" => [
"custom_date" => [
"key" => "date",
"compare" => "EXISTS",
"type" => "DATETIME",
]
],
"orderby" => [
"custom_date" => "ASC",
],
]);
Be sure to update the value for key to whatever your ACF field name is.