Home > Back-end >  How to loop custom post type using while loop in wordpress
How to loop custom post type using while loop in wordpress

Time:11-06

I am having issues in looping custom post type using while loop. Yes, I am display data without error but the_ID() function is being printed outside specific id i.e id="panelsStayOpen-heading'.the_ID().'" as shown in an image. issue


function displayFaqs() {
        
    
    $args = array(
        'post_type' => 'advance_faq',
        'posts_per_page' => '-1',
        'post_status' => 'publish'
    );
    // The Query
    $the_query = new WP_Query( $args );

    ob_start();
    // The Loop
    if ( $the_query->have_posts() ) {
        echo '<div  id="accordionPanelsStayOpenExample">';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            echo '<div >';
            echo ' <h2  id="panelsStayOpen-heading'.the_ID().'">
                    <button  type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapse'.the_ID().'" aria-expanded="true" aria-controls="panelsStayOpen-collapse'.the_ID().'">'
                      . get_the_title() . '
                    </button>
                  </h2>';
            echo '<div id="panelsStayOpen-collapse'.the_ID().'"        aria-labelledby="panelsStayOpen-heading'.the_ID().'">
                  <div >
                  '
                      .the_content() . '
                  </div>
                </div>';
        }
        echo '</div>';
        echo '</div>';
    } else {
        // no posts found
    }
    /* Restore original Post Data */
    wp_reset_postdata();

    $contents = ob_get_contents();
    ob_end_clean();
      return $contents;

}
add_action( 'init', 'a_register_shortcodes');

enter image description here How do I fix the issues to print in a specific id without printing outside

CodePudding user response:

Replace the_ID() with get_the_ID() because you are already using echo.

the_ID() used to print out the post_id directly and get_the_ID() returns the id.

  • Related