简体   繁体   中英

Wordpress– How to include custom post type content in a template?

I am using a custom post type and have got it to show up in the Wordpress admin area. This is part of my functions code:

//CUSTOM POST TYPE
add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'slick_slider',
  array(
  'labels' => array(
    'name' => __( 'Main Slider' ),
    'singular_name' => __( 'Slider' )
  ),
  'public' => true,
  'has_archive' => true,
)
);
}

My problem is that I need to insert these custom post types into a template. I've tried using this code to do that:

 <?php if (have_posts()) : while (have_posts()) : the_post();?>
     <?php $slick_slider_values = get_post_meta( get_the_ID(), 'slick_slider' ); ?>
 <?php endwhile; endif; ?>

But it does not work. Any idea what code I need to get the CPTs to display correctly within the template page?

You're using a Custom Post Type so you need to do a custom post type loop:

<?php query_posts('post_type=slick_slider&posts_per_page=5'); if ( have_posts() ) while ( have_posts() ) : the_post();?>
// normal post stuff here ie <?php the_content(); ?>
<?php endwhile; wp_reset_query(); ?>

This goes outside the loop! Hope that helps!

This would work for you:

$args = array(
  'post_type'   => 'slick_slider',
  'post_status' => 'publish',
 );

$slick_slider = new WP_Query( $args );
if( $slick_slider->have_posts() ) :

      while( $slick_slider->have_posts() ) : $slick_slider->the_post();

            $slick_slider_values = get_post_meta( get_the_ID(), 'slick_slider' );

      endwhile;
endif;

You've need to use WP_Query if you want to show any post type or post outside of single post file or outside of the page template. So use the following code instead.

$slider = new WP_Query(array(
             'post_type'   => 'slick_slider',
          ));
if( $slider->have_posts() ){
      while( $slider->have_posts() ) {
        $slider->the_post();
        $slider_meta = get_post_meta( get_the_ID(), 'slick_slider' );
    }
  wp_reset_postdata();
}

Hope that it'll help you.

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