Sort by custom meta box a custom post type - Wordpress

1

I have a custom post type called "events". In it, I have a custom meta box called date (which is the day, month and year in which the event will occur).

The problem is that I want to create a new obj WP_QUERY, I can order it by the date I entered in the custom meta box, from more recent, to more distant, and that those that have already occurred, that are not shown.

I know that the order_by exists (I put it down) but among the options I did not find any that refer to a custom meta box.

What could I do in this case?

    $paged = ( get_query_var('paged') ) ? get_query_var('paged') :1;            
    $args = array(
        'post_type'=>'eventos', 
        'posts_per_page' => 8, 
        'paged' => $paged,
        'orderby' => 'title',
        'order' => 'DESC'
    );
    // The Query
    $the_query = new WP_Query( $args );

    // The Loop
    if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            get_template_part('content-eventos');
        } 
    }
    
asked by MarisabelGC 22.03.2017 в 19:09
source

2 answers

1

It would be something like this:

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') :1;            
$hoy = date('m/d/Y', strtotime('+2 hours'));
$the_query = new WP_Query( array(
  'post_type' => 'eventos',
  'posts_per_page' => 8,
  'paged' => $paged,
  'meta_key' => 'start_date', 
  'orderby' => 'meta_value',
  'order' => 'ASC',
  'meta_query' => array(
  array(
    'key' => 'start_date',
    'value' => $hoy,
    'compare' => '>=',
    'type' => 'DATE'
  ))
));
?>
    
answered by 23.03.2017 в 05:02
1

We need to add the meta_key field and optionally the meta_query array with the filter condition.

$paged = ( get_query_var('paged') ) ? get_query_var('paged') :1;            
$args = array(
    'post_type'=>'eventos', 
    'posts_per_page' => 8, 
    'paged' => $paged,
    'meta_key' => 'campo_metabox',
    'orderby' => 'meta_value',
    'order' => 'DESC',
    'meta_query' => array(
        array(
            'key' => 'campo_metabox',
            'value' => 'valor',
            'compare' => '>=',
            'type' => 'tipo_de_variable'
        )
    ),
);
// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        get_template_part('content-eventos');
    } 
}

The variable_type can be any of the fields used in the table.

    
answered by 24.03.2017 в 07:29