挂接到的问题the_content 不能保证我们在循环中。
解决方案pre_get_posts 排除某些查询。通过the_post 挂钩前the_content.
详细信息将操作添加到pre_get_posts 具体查看页面是否为单数。
add_action( \'pre_get_posts\', \'wpse_106269_pre_get_posts\', 10, 1 );
function wpse_106269_pre_get_posts( $query ) {
if( is_singular() ) {
add_action( \'the_post\', \'wpse_106269_the_post\', 10, 2 );
}
}
将操作添加到
the_post. 当我们在的时候,每个帖子都会触发这个动作钩
the loop. 一旦我们进去
the_post, 我们知道我们在循环中,所以我们可以在
the_content.
function wpse_106269_the_post( $post, $query ) {
remove_action( \'the_post\', \'wpse_106269_the_post\', 10, 2 );
add_filter( \'the_content\', \'wpse_106269_the_content\', 10, 1 );
}
确保
the_content 筛选器仅在中激发
the_post, 删除它,以便将来不会被触发,除非
the_post 行动挂钩。
function wpse_106269_the_content( $content ) {
remove_filter( \'the_content\', \'wpse_106269_the_content\', 10, 1 );
//* Do something with $content
return $content;
}