Skip to content

Instantly share code, notes, and snippets.

@miguelpeixe
Last active August 8, 2017 20:40
Show Gist options
  • Save miguelpeixe/8596d79d77450d5782d5deaaa3898822 to your computer and use it in GitHub Desktop.
Save miguelpeixe/8596d79d77450d5782d5deaaa3898822 to your computer and use it in GitHub Desktop.
WordPress: Queries padrões por post type definidos via classe

Como está agora:

No arquivo archive-{post-type}.php:

<?php
  $posts_query = new WP_Query(array(
    'post_type' => 'pmc_timeline_item',
    'posts_per_page' => -1,
    'meta_key' => 'start_date',
    'orderby' => 'meta_value',
    'order' => 'ASC'
  ));
  while($posts_query->have_posts()) :
    $posts_query->the_post();
  endwhile;

O WordPress já inicializa a query antes de chamar o template archive-{post-type}.php. Desta forma a query está sendo executada 2 vezes.

Melhor prática:

Para casos onde quer se determinar uma query padrão para o comportamento do post type utilizamos o action hook pre_get_posts aplicado diretamente na classe que registra o post type.

<?php
class PostType {
  function __construct() {
    // outras coisas estão aqui também
    add_action('pre_get_posts', array($this, 'pre_get_posts'));
  }
  function pre_get_posts ($query) {
    $post_type = $query->get('post_type');
    
    if($post_type == 'seu_post_type' || $post_type == array('seu_post_type')) {
      $query->set('posts_per_page', -1);
      // e por aí vai
    }
  }
  // outras coisas estão aqui também
}
new PostType();

No arquivo archive-{post-type}.php:

<?php
if(have_posts()) : while(have_posts()) : the_post();

endwhile; endif;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment