skip to Main Content

I have a lot of custom post types created with acf. When searched, there are results thanks to acf better search. I created single-{}.php in my child theme to show details of the post clicked. But I can’t get the field details on it.

Codes like this arent working(have_posts() alsways returning false):

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <h1><?php the_title(); ?></h1>
    <div class="post-content">
        <?php the_content(); ?>
        <p><?php get_field('field_name'); ?></p>
    </div>
<?php endwhile; endif; ?>

I can get field data with this but I want the specific data from the post clicked:

$args = array(
    'post_type' => 'your_custom_post_type', // Replace with your custom post type
    'posts_per_page' => 10, // Adjust as needed
);

$block_query = new WP_Query($args);

if ($block_query->have_posts()) {
    while ($block_query->have_posts()) {
        $block_query->the_post();
        // Your code to display each post goes here
    }
    wp_reset_postdata();
} else {
    echo '<p>No posts found.</p>';
}

I’m new to wordpress so I’m probibly being stupid. Could you help me with this?

2

Answers


  1. To achieve this in addition to the Template Name file header, the post types supported by a template can be specified using Template Post Type: as following.

    <?php
    /*
    Template Name: Custom page layout
    Template Post Type: custom_slug 
    */
    

    Template Post Type you need to pass the slug of your CPT.

    Read more here

    Login or Signup to reply.
  2. <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <h1><?php the_title(); ?></h1>
        <div class="post-content">
            <?php the_content(); ?>
            <p><?php get_field('field_name'); ?></p>
        </div>
    <?php endwhile; endif; ?>
    

    The above code is the correct loop to display single post data.

    1. Maybe start with creating a single.php file and see if you can view the custom post type single view.
    2. Then make sure your custom post type slug is correct. WP and acf uses singular and plural names E.g events and event. Test out single-event.php

    This is gold as shared in above post https://developer.wordpress.org/themes/template-files-section/custom-post-type-template-files/
    https://www.advancedcustomfields.com/resources/registering-a-custom-post-type/

    It will also help if you share your ACF settings

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search