在主题中,我使用customizer显示帖子之前(和之后)的内容、单个帖子等。
/**
Page Before Category
*/
$wp_customize->add_setting( \'content_before_category\', array(
\'default\' => 0,
\'sanitize_callback\' => \'theme_name_sanitize_integer\',
) );
$wp_customize->add_control( \'content_before_category\', array(
\'label\' => esc_html__( \'Page Before Category\', \'theme_name\' ),
\'description\' => esc_html__( \'Content of the selected page will be shown on Blog Page before all posts.\', \'theme_name\' ),
\'type\' => \'dropdown-pages\',
\'section\' => \'section_blog\',
) );
然后在
index.php
我用过
$content_before_category = get_theme_mod( \'content_before_category\', false );
if ( $content_before_category ) {
$page_id = get_page( $content_before_category );
echo apply_filters( \'the_content\', $page_id->post_content ); // WPCS: xss ok.
}
但有人告诉我
the_content
直接过滤是不好的,因为它可能会破坏插件
as described here.
因此,我做了以下工作:
在我的functions.php
我补充道
if ( ! function_exists( \'mytheme_content_filter\' ) ) {
/**
* Default content filter
*
* @param string $content Post content.
* @return string Post content.
*/
function mytheme_content_filter( $content ) {
return $content;
}
}
/**
* Adds custom filter that filters the content and is used instead of \'the_content\' filter.
*/
add_filter( \'mytheme_content_filter\', \'wptexturize\' );
add_filter( \'mytheme_content_filter\', \'convert_smilies\' );
add_filter( \'mytheme_content_filter\', \'convert_chars\' );
add_filter( \'mytheme_content_filter\', \'wpautop\' );
add_filter( \'mytheme_content_filter\', \'shortcode_unautop\' );
add_filter( \'mytheme_content_filter\', \'do_shortcode\' );
然后将过滤器更改为
$content_before_category = get_theme_mod( \'content_before_category\', false );
if ( $content_before_category ) {
$page_id = get_page( $content_before_category );
echo apply_filters( \'mytheme_content_filter\', $page_id->post_content ); // WPCS: xss ok.
}
它适用于除嵌入式内容以外的所有内容。
youtube视频、推特将无法正常呈现。
我尝试搜索嵌入筛选器,但找不到。
有什么建议吗?
最合适的回答,由SO网友:cybmeta 整理而成
the_content
过滤器和其他过滤器一样好。问题是,它应该与glogal一起在一个循环中运行$post
正确设置为循环中的当前post。因此,您可以这样做(未经测试,仅作为示例编写):
$content_before_category = get_theme_mod( \'content_before_category\', false );
if ( $content_before_category ) {
global $post;
// get_page() is deprecated; use get_post() instead
// $page_id = get_page( $content_before_category );
$post = get_post( $content_before_category );
// Setup global post data with our page
setup_postdata( $post );
// Output the content
the_content();
// Reset global post data
wp_reset_postdata();
}
如果希望运行自定义筛选器,可以。嵌入内容的问题是,您没有运行自动embbed过滤器;只需添加它:
global $wp_embed;
add_filter( \'mytheme_content_filter\', array( $wp_embed, \'autoembed\') );