Displaying Custom Post Type on Front End - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Tuesday, February 2, 2021

Displaying Custom Post Type on Front End

 Let’s assume that you have successfully created a post for your WordPress website. discussed in previous post. Now you want to add this post as a custom post type on your WordPress website. and then add dummy News posts to your site.



Creating a Template

Once, you wrote the code, create a new file called template-news.php and place it in your theme folder,  add the following code to it.


<?php
/*Template Name: News*/
get_header();
query_posts(array(
   'post_type' => 'news'
)); ?>
<?php
while (have_posts()) : the_post(); ?>
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<?php endwhile;
get_footer();
?>

Selecting a Template

Now create a new page called News from the Pages option in your WordPress dashboard and access it. You can see a Template option available in Page Attributes on the right side of your screen. Select the new template News and then click the update button. For further reference, check out the image below.



Adding a Menu for CPT

To add your new custom post type as a part of the Menu options on your WordPress website, navigate to Appearance → Menus and add the News page to your main menu. like shown in figure



as a result your menu item will be updated with CPT

Display Detail of Custom Post Type

For displaying details of custom post types we need a page which is called single-cpt name and in our case called single-news.php create this file and store in root directory of your  WordPress theme and then add the following code to it.

<?php
get_header();
/* Start the Loop */
while (have_posts()) : the_post();
   get_template_part('template-parts/post/content', get_post_format());
endwhile; // End of the loop.
get_footer();
?>
after adding  this code you will be able to view all details of the posts.

Conclusion

Well, you have now learned the way to create a Custom Post Type in WordPress, a pretty complex thing to do. You learned to create cpt from backend and then display it on the frontend using the template. With this you'll be able to achieve basic knowledge of cpt 

 


No comments:

Post a Comment

Post Top Ad