Filtering on date fields

Support MB Views Filtering on date fieldsResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #37048
    ArnoArno
    Participant

    Hi,

    I have a view with this query:

    {% set terms_to_match = mb.wp_get_post_terms(post.ID, taxonomy_to_match, {fields: 'slugs'}) %}
    
    {% set args = {
    post_type: 'promotion',
    numberposts: 3,
    sort_column: 'content_popularity',
    order: 'ASC',
    tax_query: [ {
    	taxonomy: taxonomy_to_match,
    	field: 'slug',
    	terms: terms_to_match} ]
    } %}
    {% set posts = mb.get_posts(args) %}

    This works fine. I wanted to add filtering on dates. I tried to add this to the arguments:

    meta_query: [
    {key: gmdate,
    value: ['promotion_start_date', 'promotion_end_date'],
    compare: 'between',
    type: 'DATE'
    }],

    and this:

    meta_query: [{
    key: 'promotion_start_date',
    value: gmdate,
    compare: '<=',
    type: 'DATE'
    },
    {
    key: 'promotion_end_date',
    value: gmdate,
    compare: '>=',
    type: 'DATE'
    }],

    The query gets executed (no syntax errors) but it does not get me the results I expect. What do need to do to get posts that have their start date before the current date+time and their end date after?

    The dates are in Datetime Picker fields.

    #37055
    Long NguyenLong Nguyen
    Moderator

    Hi,

    I think the code should be

    meta_query: [{
    key: 'promotion_start_date',
    value: 'now'|date("Y-m-d"), //change to how promotion_start_date is stored
    compare: '<=',
    },
    {
    key: 'promotion_end_date',
    value: 'now'|date("Y-m-d"), //change to how promotion_end_date is stored,
    compare: '>=',
    }],

    Refer to the documentation https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters
    and this topic https://stackoverflow.com/questions/28285722/wordpress-query-by-custom-field-with-date-type

    #37056
    ArnoArno
    Participant

    Hi Long,

    Thanks, that helped me out. Here's what I ended up with to make it compare on time too:

    meta_query: [{
    key: 'promotion_start_date',
    value: 'now'|date("Y-m-d H:i"),
    compare: '<=',
    },
    {
    key: 'promotion_end_date',
    value: 'now'|date("Y-m-d H:i"),
    compare: '>=',
    }],
Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.