简体   繁体   中英

Displaying Posts from a specific category in WordPress

I can see countless posts regarding this question all over the web, but no matter how many study, I can't seem to get this to work. Could someone help me understand why the code I have isn't working correctly?

To break it down, I have created a custom page template and replicated the code from page.php (Default Template). I have then included my args and my post loop, as shown below;

<main class="site-main" id="main">

  <?php
    // The Arguments
    $args = array(
      'category_name'  => 'commercial',
      'post_type'      => 'post',
      'post_status'    => 'publish',
      'posts_per_page' => 6
    );  

    // The Query
    $the_query = new WP_Query( $args ); 
    // If posts...
    if ( $the_query->have_posts() ) : ?>

  <!-- Start the loop -->
  <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
  <?php get_template_part( 'content', 'works' ); ?>  
  <?php endwhile; endif; // end the loop. ?>
  <?php wp_reset_postdata(); ?>

</main>

The category I'm trying to target is 'commercial'.

From the front end I get a fully functioning page, no visual errors and everything is displayed correctly. Plainly put it's simply blank. As if the page isn't loading the posts.

My question Is there anything wrong with my code structure? Or any noticeable syntax errors to experienced WP devs?

Note: Unfortunately, most of the examples I've found on the web are fairly old. I worry that the structure of these examples are out of date. So I have tried to build my loop via the code provided from the docs.

I also tried the route outlined in the docs ;

$the_query = new WP_Query( array( 'category_name' => 'commercial' ) );

No luck sadly. :(

Any help would be greatly appreciated.

Thanks in advance, Regards, -B.

EDIT: Sun 7th Oct 2018 17:11 (Answered)

Thanks to @msg's suggestion I can see I was loading the incorrect file path for my loop template. I was so obsessed with the loop, I forgot about it.

EDIT: Sun 7th Oct 2018 17:11

After running the following I can see the posts have been collected.

    echo "<pre>";
        print_r($the_query);
    echo "</pre>";

The query seems ok. If you are getting results the problem most likely is in the template.

The get_template_part call is trying to load content-works.php and as a quirk of this function, is failing silently if it can't find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM