skip to Main Content

I think I’m missing something obvious here!
I’m creating my first child theme based on the WordPress TwentyTwentyOne theme. I want to display posts from a particular category (e.g. ‘news’) on my home page. I created a specific page template "page-home.php", a copy of "page-php" from the parent theme, but with the following code added:

$args = array(
   'category_name' => 'news',
   'posts_per_page' => 3
);
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) {
   while ( $my_query->have_posts() ) {
      $my_query->the_post();     
   }
}
wp_reset_postdata();

This does not work. The Eclipse IDE shows an error on the "new WP_Query()": "WP_Query cannot be resolved to a type", which is understandable, as the project does not include the wp-include directory. However, I’d expected the WordPress environment to have added this, which doesn’t seem to be the case.

I then added the following, rather convoluted code

$filename = $_SERVER["SCRIPT_FILENAME"];
$dir = substr($filename,0, strrpos($filename,"/"));
$incPath = $dir."/wp-includes";
$incPath = str_replace("/", DIRECTORY_SEPARATOR, $incPath);
set_include_path(get_include_path() . PATH_SEPARATOR . $incPath);
require_once 'class-wp-query.php';

This does not help either.

I get the feeling that there’s something obvious I’m missing, it shouldn’t be so complicated.

I’m running WordPress 5.7 on Windows 10.0.19041 with Apache 2.4 and PHP 7.4.

2

Answers


  1. Chosen as BEST ANSWER

    I've added the line

    echo '<li>' . get_the_title() . '</li>';
    

    as suggested by Aleksandr, and the page now outputs the required titles.


  2. It works just fine for me:

    <?php
    $args = array(
        'posts_per_page' => 3,
    );
    $the_query = new WP_Query($args);
    
    if ($the_query->have_posts()) {
        echo '<ul>';
        while ($the_query->have_posts()) {
            $the_query->the_post();
            echo '<li>' . get_the_title() . '</li>';
        }
        echo '</ul>';
    } else {
        // no posts found
    }
    
    wp_reset_postdata();
    
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search