0

I created a custom post type in the mu-plugins folder.

function wpdocs_codex_book_init() {
    $labels = array(
        'name'                  => _x( 'Books', 'Post type general name', 'textdomain' ),
        'singular_name'         => _x( 'book', 'Post type singular name', 'textdomain' ),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
    );

    register_post_type( 'book', $args );
}

add_action( 'init', 'wpdocs_codex_book_init' ); 

When it comes to render the content of it in the single-book.php page I create the custom query and I use this code:

<?php
$args = array(
    'post_type' => 'book',
);
$query = new WP_Query( $args ); 
?>

<h1><?php the_title(); ?></h1>
<h1><?php the_content(); ?></h1>

the title is rendered correctly but when it comes to the content it throws this error:

Warning: count(): Parameter must be an array or an object that implements Countable in /app/public/wp-includes/post-template.php on line 284

The default posts and the pages are, instead, rendered correctly. Why is this happening? Thanks in advance

  • Why are you creating a new query in the template? Does it work correctly if you remove your query code? – Milo Jan 14 at 13:58
  • totally my bad. Wordpress has already identified the correct query since i created the single-book itself. – Enrico Jan 14 at 14:09
2

single-book.php should not have a custom query in it. WordPress has already queried the correct post, so new WP_Query( $args ) is completely unnecessary.

Your problem is that you're missing the loop.

At the bare minimum single-book.php should have:

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

    <h1><?php the_title(); ?></h1>

    <?php the_content(); ?>

<?php endwhile; ?>
  • Definitely working. My concern was that using the loop every title and content of every book-post would have displayed, but that is is because the custom query was totally unnecessary. – Enrico Jan 14 at 14:08
  • The loop doesn't loop over every post. It loops over every post in the main query. The main query is run by WordPress and what it contains is determined by the current URL. On a single post it will only include the current post being views. On category archives it will only include the current page's worth of posts in the current category. Only use WP_Query if you intend to query for posts other than the ones that WordPress has already queried. – Jacob Peattie Jan 14 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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