这里有一个简单的技巧,可以帮助你实现你想做的任何事情:警告:这只在2616和217个主题上测试,所以它可能对你当前的主题有用,也可能对你当前的主题无效。
class VirtualPage {
/**
* @var int $page_id The ID of the page where you would want to inject your custom template.
**/
var $page_id = 0;
/**
* @var (mixed) $callback The callback function/method that will be called to replace the current post.
**/
var $callback = false;
function __construct( $page_id, $callback = false ) {
$this->page_id = $page_id;
$this->callback = $callback;
/**
* Set the injector when there are posts found.
**/
add_action( \'posts_results\', array( $this, \'posts_results\' ), 10, 2 );
}
function posts_results( $posts, $wp ) {
if ( $wp->is_main_query()
&& $wp->is_singular
&& count( $posts ) > 0
&& $posts[0]->ID == $this->page_id ) {
$found_posts = count( $posts );
/**
* $wp->post_count holds the number of iterated posts. We\'ll make WP believe that all
* posts are iterated.
**/
$wp->post_count = $found_posts;
/**
* $wp->current_post holds the current post index. Setting it to the last post index
* will immediately trigger `loop_end` action hook.
**/
$wp->current_post = $found_posts - 1;
add_action( \'loop_end\', array( $this, \'loop_end\' ) );
/**
* Immediately remove the hook!
**/
remove_action( \'posts_results\', array( $this, \'posts_results\' ), 10, 2 );
}
return $posts;
}
function loop_end() {
if ( $this->callback ) {
// Call your callback here or do your stuff here
call_user_func( $this->callback );
}
/**
* Immediately remove the hook!
**/
remove_action( \'loop_end\', array( $this, \'loop_end\' ) );
}
}