- This topic has 4 replies, 3 voices, and was last updated 7 years, 3 months ago by
Jason.
-
AuthorPosts
-
-
October 22, 2014 at 5:02 am #2608
ebarrosoMemberHi,
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!
-
October 22, 2014 at 10:51 am #2616
SteveKeymaster@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.
-
October 22, 2014 at 10:56 am #2617
JasonKeymasterYou 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!
-
October 22, 2014 at 11:07 am #2618
-
October 22, 2014 at 11:13 am #2619
JasonKeymaster@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.
-
-
AuthorPosts
- The topic ‘How to call a Custom Post from "Single.php"’ is closed to new replies.