Search code examples
phpwordpresspaginationwidgetcustom-post-type

What is the right way to present custom post type in WordPress?


PRECONDITION:

  1. I created custom post type "comparison"
  2. I created 'widget.php' and registered it in 'functions.php'
  3. I added widget to 'front-page.php'

TASK: On my Front Page and I want to list all posts with type "comparison" in separate widget with pagination

PROBLEM: I don't know the 'best practice', how to implement it technically. How to list all "comparison" in widget?


Solution

  • Here is the custom post template code, You can assign the template on the page you want to display the posts list. You can try with below template code:

    <?php 
    # Template Name: Comparison List 
    ?>
    
    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array( 
              'posts_per_page' => 15, 
              'paged' => $paged, 
              'post_type' => 'comparison', 
              'orderby' => 'title', 
              'order' => 'asc' 
            );
    $wp_query = new WP_Query($args);
    ?>
    
    <?php get_header(); ?>
    
    <?php if ($wp_query->have_posts()) : ?>
    
        <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
    
            <?php get_template_part( 'template-parts/content', 'comparison-list-item' ); ?>
    
        <?php endwhile; ?>
    
        <?php print_pagination($wp_query); ?>
    
    <?php else: ?>
    
    <?php get_template_part( 'template-parts/content', 'nothing-found' ); ?>
    
    <?php endif; ?>
    
    <?php wp_reset_postdata(); ?>
    
    <?php get_footer(); ?>