简体   繁体   中英

Change page template to show Custom Post Type in Wordpress

I have this Page Template, developed by someone else a long long time ago, which shows all my Posts in a grid based on the category they're in.

Now, I want to have such a page for my Custom Post Type but I can't get it to work. I tried replacing the

<?php if (have_posts()) : while (have_posts()) : the_post();?>

with

<?php $args = array('post_type'=>array('shopitems')); query_posts($args); if ( 
have_posts() ) : while ( have_posts() ) : the_post();?>`

which seems to be the go-to answer everywhere I look. but for me, it turns out empty. Below the original Page Template, I want to change this so it loads the 'shopitems' Custom Post Type.

Any help or nod in the right direction is greatly appreciated!

<?php get_header(); ?>
<div class="content-sidebar-wrap">
    <?php if (have_posts()) : while (have_posts()) : the_post();?>
  <?php $category_list= get_the_content(); ?>
<?php endwhile; endif; ?>
    <div id="content" class="post-category page">
    <?php $category_name=explode(',', $category_list);
     $catIDs="";
        foreach ($category_name as $cat_name) {
            $catIDs.= get_cat_ID(trim($cat_name)).",";
          } 
          $catIDs=trim($catIDs,","); 
          $i=0;
    ?>  
        <?php $thePosts= query_posts('cat='.$catIDs.'&post_status=publish&posts_per_page=-1'); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
     <?php if (has_post_thumbnail( $post->ID ) ) { ?>
        <?php // $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
        <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) ); ?>
       <?php if($i%4==0) { ?>
       <div class="clear"></div>
       <?php } $i++; ?>
      <div class="thumb">
        <a href="<?php the_permalink(); ?>">
         <img alt="" src="<?php echo $image[0]; ?>" class="thumb-img"> 
         <span class="thumb-title">
            <?php 
            $second_name = get_field('second_name');
            if( $second_name && !empty($second_name))
                echo $second_name;
            else
            the_title(); 
            ?>
         </span> 
        </a>
      </div>
        <?php } endwhile; else: endif; ?>
    </div>
</div>
<?php get_footer(); ?>

Just you need to modify your query like below.

<?php 
$args = array(
           'post_type'=>'shopitems'
        );
 $query = new WP_Query($args);
if ($query->have_posts() ) : 
while ( $query->have_posts() ) : $query->the_post();
//do your code here

endwhile;

else:
  // No posts found
endif;


?>`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM