Tagged: ,

This topic contains 4 replies, has 3 voices, and was last updated by  Jason 4 years, 12 months ago.

  • Author
    Posts
  • #2608

    ebarroso
    Participant

    Hi,

    Actually I call the custom post (called qps) with this code:

    <?php
    $args=array(  
      'post_type' => 'qps'
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a><?php the_title(); ?></a></p>
         <p><a><?php echo get_post_meta($post->ID, 'qpstext2', true); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  
    ?>

    But, i just want to know if there is another way to do that, cause i think this is so much code for only one arg: “post_type”.

    Thanks!

  • #2616

    Steve
    Keymaster

    @ebarroso– When you click on a link to a custom post, single.php should automatically work with a standard WordPress loop. WordPress has a template hierarchy, which you can find here if you want to do something different with this Post Type, you create a single-qps.php file, as defined in the hierarchy.

    Let me know if that helps.

  • #2617

    Jason
    Keymaster

    You could also use the get_posts function, which would return you an array of WP_Post objects. You’d then loop through them with a foreach. This is my preferred method.

    $posts = get_posts(array(
      'post_type'  => 'qps',
      'numberposts'=> -1
    ));
    
    foreach($posts as $post) {
      $url = get_post_permalink($post->ID);
      echo "<p><a href='$url'>$post->post_title</a></p>";
      // etc..
    }

    Note, however, that if you use get_posts you handle the array of objects like you would any other time in PHP. You can no longer use the loop functions (e.g. the_title(), the_content(), etc.) as you’re not using the wp_query object and are therefore not inside “the loop”.

    Hope this helps!

  • #2618

    ebarroso
    Participant

    Hi @Steve, thanks for your reply, it helps me so much.
    @jason, your method is useful, i will do that next time.

  • #2619

    Jason
    Keymaster

    @ebarroso: It’s important to understand that the function I suggested shouldn’t be used inside something like single.php to get the posts you should be already getting. Doing this would be redundantly querying the posts again after WordPress has already done this for you. Follow what Steve put up concerning the template hierarchy.

    The get_posts function is useful in a context where the posts aren’t already queried. For example, if you want to grab the recent blog posts on the home page.

The topic ‘How to call a Custom Post from "Single.php"’ is closed to new replies.