WordPress自定义帖子类型从single.php获取模板,需要解决方案

时间:2017-10-02 21:36:52

标签: wordpress

我正在开发一个WordPress主题,我注册了一个这样的自定义帖子类型:

register_post_type('servicesDetails', array(
    'labels' => array(
        'name' => 'Services Details',
        'add_new_item' => 'Add New Post'
    ),
    'public' => true,
    'supports' => array('title', 'editor', 'thumbnail')
));

在我的front-page.php上,我将HTML编码为:

<div class="container">
    <?php 
    $servicesDetails = new WP_Query(array(
        'post_type' => 'servicesDetails'
    ));

    while ($servicesDetails->have_posts()) :
        ?>
        <div class="row">
            <?php
            for ($counter = 0; $counter < 3; $counter++) :
                $servicesDetails->the_post();
                ?>
                <div class="col-sm-4" id="featurePost">
                    <a href="<?php the_permalink(); ?>"><h3><?php the_title(); ?></h3></a>
                    <p><?php the_content(); ?></p>
                </div>
                <?php
            endfor;
            ?>
        </div>
        <?php
    endwhile;
    ?>
    </div>

当我打开一个名为single-servicesDetails.pho的文件时,WordPress没有从该文件中获取模板,它正在从single.php模板获取模板,当我删除single.php时,它正在使用index.php中的模板。

有没有人能解决这个问题?

1 个答案:

答案 0 :(得分:0)

//create custom post type

function create_post_type() {
  register_post_type( 'acme_product',
    array(
      'labels' => array(
        'name' => __( 'Products' ),
        'singular_name' => __( 'Product' )
      ),
      'public' => true,
      'has_archive' => true,
    )
  );
}
add_action( 'init', 'create_post_type' );

/* on the front-page.php - This will change the default front page ie your homepage.
posts_per_page does the loop counts for you. You do not need the for loop again in your code.
*/
<div class="container">
 <div class="row">
<?php 
$args = array( 'post_type' => 'product', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>

   <div class="col-sm-4" id="featurePost">
      <a href="<?php the_permalink(); ?>"><h3><?php the_title(); ?></h3></a>
      <p><?php the_content(); ?></p>
   </div>
<?php endwhile; ?>

 </div>