如果记得很清楚的话,我从这里得到了这个技巧:Use template_include with custom post types.
我们使用的插件将生成一个;“虚拟模板”;对于给定的职位类型。过滤器template_include
将呈现位于插件文件夹中的模板文件。
您必须优化函数custom_template
和模板文件,以满足您的需要。希望这有帮助;)
插件文件adjust the post_type
name in the class instantiation
<?php
! defined( \'ABSPATH\' ) AND exit;
/*
Plugin Name: Virtual Template for CPT
Plugin URI: https://wordpress.stackexchange.com/q/75307/12615
Description: Use the plugin\'s template file to render an outsider loop.
Author: brasofilo
Author URI: https://wordpress.stackexchange.com/users/12615/brasofilo
Version: 2012.12.11
License: GPLv2
*/
$virtual_template = new VirtualTemplateForCPT_class( \'movies\' );
class VirtualTemplateForCPT_class
{
private $pt;
private $url;
private $path;
/**
* Construct
*
* @return void
**/
public function __construct( $pt )
{
$this->pt = $pt;
$this->url = plugins_url( \'\', __FILE__ );
$this->path = plugin_dir_path( __FILE__ );
add_action( \'init\', array( $this, \'init_all\' ) );
}
/**
* Dispatch general hooks
*
* @return void
**/
public function init_all()
{
add_action( \'wp_enqueue_scripts\', array( $this, \'frontend_enqueue\' ) );
add_filter( \'body_class\', array( $this, \'add_body_class\' ) );
add_filter( \'template_include\', array( $this, \'custom_template\' ) );
}
/**
* Use for custom frontend enqueues of scripts and styles
* http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts
*
* @return void
**/
public function frontend_enqueue()
{
global $post;
if( $this->pt != get_post_type( $post->ID ) )
return;
}
/**
* Add custom class to body tag
* http://codex.wordpress.org/Function_Reference/body_class
*
* @param array $classes
* @return array
**/
public function add_body_class( $classes )
{
global $post;
if( $this->pt != get_post_type( $post->ID ) )
return $classes;
$classes[] = $this->pt . \'-body-class\';
return $classes;
}
/**
* Use the plugin template file to display the CPT
* http://codex.wordpress.org/Conditional_Tags
*
* @param string $template
* @return string
**/
public function custom_template( $template )
{
$post_types = array( $this->pt );
$theme = wp_get_theme();
if ( is_post_type_archive( $post_types ) )
$template = $this->path . \'/single-virtual-cpt.php\';
if ( is_singular( $post_types ) )
$template = $this->path . \'/single-virtual-cpt.php\';
return $template;
}
}
模板文件
single-virtual-cpt.php
将插件文件放在同一文件夹中
<?php
/**
* A custom -not from the theme- template
*
* @package WordPress
* @subpackage Virtual_Template
*/
get_header();
while ( have_posts() ) : the_post(); $theID = $post->ID;
_e(\'This is a virtual template for the post:<br />\');
the_title();
endwhile;
get_footer();
?>
</body>
</html>
结果
单击放大⤴