5

I have a custom post type for events set up and am displaying the posts in a custom post type archive "archive-events.php".

I am using Advanced Custom Fields to put an event date "event_date" on each post, chosen by the user. The date is outputting in the format "yyyymmdd" example: "20141129".

I have it setup so that if an event date is more than two days old it doesn't show up; hiding events that have passed. This function is working properly.

The problem is that for some reason I cannot change the sort order of the posts. I want to order the events so that the closest date appears first so people know which events are coming up. So I would be ordering the posts by the "event_date".

I've spent three hours going through similar problems and trying to implement their code to no avail. I've tried the code on various other pages and archives in simple forms and it doesn't work there either. I have gotten to a point where it seems the custom post type is the problem not the query.

I feel like I am missing part of my question because everyone else is getting the right answers but none of them are solving my problem.

I've included some of my references in the code for building the query.

UPDATE: I've discovered that the code does indeed work when I make the exact same post type but call it "event" instead of "events". Is there a reason why this might be the case? I've been looking through the database to see if I can spot a problem and I can't find anything too suspicious.

There is an entry in wp_postmeta - meta_key rule with the meta_value being: a:5{s:5:"param";s:9:"post_type";s:8:"operator";s:2:"==";s:5:"value";s:6:"events";s:8:"order_no";i:0;s:8:"group_no";i:0;}

That could be a problem but I tried deleting that line and nothing seemed to change.

Inside archive-events.php

<?php

        // http://www.advancedcustomfields.com/resources/filter-posts-by-custom-fields/
        // See also: http://www.smashingmagazine.com/2009/06/10/10-useful-wordpress-loop-hacks/
        // See also: http://wordpress.org/support/topic/query_posts-less-than-6-months-old

        // Show posts between now and X months ago.
        // http://thewichitacomputerguy.com/blog/php-date-datecreate-strtotime-options
        // http://codex.wordpress.org/Class_Reference/WP_Meta_Query

        // Clue: We are trying to order posts on a an archive page here.
        // https://wordpress.stackexchange.com/questions/167441/ascending-order-custom-post-type

        /*
            These queries check to see if the event date has come. If the date more than two days ago it moves it into the past events section. This may need to change depening on how long some events go for. This algorithm assumes events only go for a day but it's possible an event could go for a month.
        */

        // Get the date from two days ago.
        $date_1 = date('Ymd', strtotime("2 days ago"));

        $args = array(
            'post_type'         => 'events',
            'posts_per_page'    => -1,
            'meta_key'          => 'event_date',
            'orderby'           => 'meta_value_num',
            'order'             => 'ASC',
            // This line ignores plugin ordering.
            'suppress_filters'  => true,
            'meta_query'        => array(
                array(
                    // Is the event less then two days past?
                    'key'       => 'event_date',
                    'value'     => $date_1,
                    'type'      => 'numeric',
                    'compare'   => '>'
                )
            )
        );

        // query
        $wp_query = new WP_Query( $args );

        if ( $wp_query->have_posts() ) {

            // loop
            while( $wp_query->have_posts() )
            {
              $wp_query->the_post();

              get_template_part( 'content', 'events');

            }
        } else {
            // no posts found
        }

        // Reset query
        wp_reset_postdata();

        ?>

Inside functions.php

/**
 * Create Custom Post Type "Events".
 */

function lc_events_post_type() {

$labels = array(
    'name'                => _x( 'Events', 'Post Type General Name', 'leederville-connect' ),
    'singular_name'       => _x( 'Event', 'Post Type Singular Name', 'leederville-connect' ),
    'menu_name'           => __( 'Events', 'leederville-connect' ),
    'parent_item_colon'   => __( 'Event:', 'leederville-connect' ),
    'all_items'           => __( 'All Events', 'leederville-connect' ),
    'view_item'           => __( 'View Event', 'leederville-connect' ),
    'add_new_item'        => __( 'Add New Event', 'leederville-connect' ),
    'add_new'             => __( 'Add New Event', 'leederville-connect' ),
    'edit_item'           => __( 'Edit Event', 'leederville-connect' ),
    'update_item'         => __( 'Update Event', 'leederville-connect' ),
    'search_items'        => __( 'Search Events', 'leederville-connect' ),
    'not_found'           => __( 'Event Not found', 'leederville-connect' ),
    'not_found_in_trash'  => __( 'Event Not Found in Trash', 'leederville-connect' ),
);
$args = array(
    'label'               => __( 'events', 'leederville-connect' ),
    'description'         => __( 'The latest events in Leederville.', 'leederville-connect' ),
    'labels'              => $labels,
    'supports'            => array( 'title' ),
    'taxonomies'          => array( 'event_category' ),
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'menu_position'       => 5,
    'menu_icon'           => 'dashicons-calendar',
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'post',
);
register_post_type( 'events', $args );

}

// Hook into the 'init' action
add_action( 'init', 'lc_events_post_type', 0 );

Some Related Questions

  • The answer to the first question you linked is the answer to yours- you don't set meta_key argument anywhere for the order. – Milo Nov 25 '14 at 14:49
  • I did actually try that without success; I neglected to put that line of code back into the query for this. Unless I have somehow used the wrong key it hasn't helped. – Jake Nov 26 '14 at 2:43
5

I have solved my problem and it had nothing to do with the query, the database or the post type.

The problem was that in trying to initially construct the query I had left a pre_get_posts function in my functions.php which was conflicting with my query. The lesson here for me is to make sure I have thoroughly checked ALL files.

The offending counter code:

// Events Pre Get Posts

function my_pre_get_posts( $query )
{
    // validate
    if( is_admin() )
    {
        return $query;
    }


    if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'events' )
    {
        $query->set('orderby', 'meta_value_num');
        $query->set('meta_key', 'event_date');
        $query->set('order', 'DESC');
    }

    // always return
    return $query;

}

add_action('pre_get_posts', 'my_pre_get_posts');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.