The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS WP: possible to filter a query based on substring of custom field value?

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #45989

    I have a custom post type called ‘events’. This type has a custom field (‘eventdate’) with the date for the event. This date is always formatted like yyyymmdd (so for today it would be 20130719). So for a normal query, sorted by the value of this custom field, I did this:

    query_posts( ‘post_type=events&meta_key=eventdate&orderby=meta_value’ );

    while ( have_posts() ) : the_post();
    // and other stuff….


    And this will list all events. But now I want to list events for 2012 only — so ONLY the posts where the first four characters of the value of the eventdate custom field are ‘2012’. Is there a (fairly easy) way to work this in the query? If it’s going to take dozens of lines of code, then never mind…. I don’t want to overcomplicated it, but just checking if it’s possible to do. Or would I be better off using three custom fields (eventyear, eventmonth, eventday)?

    I don’t want to query everything and then show (or not show) based on that criterium — I really want to work it in the actual query (because I need proper pagination and such).


    Problem solved:

    query_posts (
    ‘post_type’=> ‘events’,
    ‘orderby’ => ‘meta_value’,
    ‘meta_key’ => ‘eventdate’,
    ‘order’ => ‘asc’,
    ‘meta_query’ => array(
    ‘key’ => ‘eventdate’,
    ‘value’ => ‘2012’,
    ‘compare’ => ‘LIKE’

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘CSS’ is closed to new topics and replies.