1

Something is really tripping me up. I have been used to querying posts via custom queries however based on research lately I have learned that for the most part this is a big no no. So, in testing the standard wp loop, I realized it does not work on for example, page-mypage.php. Can anyone share insight on this?

If I do something like get_title, it just gives the title for that page. I realize there is other posts about this topic on stack but all the up-voted responses are to use a custom query which again, as I have understood, is a poor method and pre_get_posts should be used instead. However, I tried using pre_get_posts function and that did not work either.

add_action( 'pre_get_posts', 'display_posts' );
function display_posts( $query ) {
if ( ! is_admin() && $query->is_main_query()) {
} // end if;
} 

Does the standard loop only work on index.php? So I am assuming the global query does not run before page.php is called? Im totally confused here as well because how would wp know to display posts on, for example, page-mypage.php unless you are querying them directly in the template?

Again, I am using the standard loop, and it is not displaying any post data.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; endif; ?>

1 Answer 1

0

You can use custom query to show post in your template


$args = array(
    'post_type' => 'product',
    'posts_per_page' => 10
  );
  $loop = new WP_Query( $args );
  while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    the_content();
  endwhile;

2
  • 1
    Thanks for the response. But doesnt this not go against best practice? Should I be using pre_get_posts instead?
    – James
    Jan 24, 2019 at 5:36
  • i think you can create custom post type archive page template to show your post according to your query. Jan 24, 2019 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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