如何限制add_action/remove_action仅作用于Storefront主题的新闻博客页面
解决Storefront主题自定义博客页面Action仅作用于指定页面的问题
你的代码核心问题是使用了init钩子,这个钩子触发时机过早——WordPress还未完成当前页面的查询工作,导致is_page()、is_posts_page()这类页面判断函数无法返回正确结果,所以你的action移除和添加操作会作用到所有页面,包括自定义文章类型页面。
修改方案:更换钩子并添加正确的页面判断
将钩子从init换成template_redirect(或wp钩子,二者均在页面查询完成后触发),再结合准确的页面判断条件,就能让你的自定义操作仅作用于指定的新闻博客页面:
add_action( 'template_redirect', 'remove_storefront_actions' ); function remove_storefront_actions() { // 针对设置为博客的静态页面:判断当前是否是博客首页,且对应页面ID为你设置的新闻页面ID if ( is_home() && get_option( 'page_for_posts' ) == get_the_ID() ) { remove_action( 'storefront_loop_post', 'storefront_post_taxonomy', 40 ); remove_action( 'storefront_post_header_before', 'storefront_post_meta', 10 ); remove_action( 'storefront_loop_post', 'storefront_post_header', 10 ); remove_action( 'storefront_loop_post', 'storefront_post_content', 30 ); add_action( 'storefront_loop_post', 'jk_custom_storefront_post_content', 30 ); } // 如果你是直接用slug为"news"的静态页面展示新闻(未设置为博客首页),可替换为以下判断: // if ( is_page( 'news' ) ) { // // 同上的remove_action和add_action代码 // } } function jk_custom_storefront_post_content() { ?> <div class="entry-content" itemprop="articleBody"> <div class="grid grid-21 grid-news"> <div class="box txt"> <h3><?php the_title() ?></h3> <?php the_excerpt(); ?> <?php echo '<p><a class="btn-alt" href="'.get_permalink().'">Read More</a></p>'; ?> </div> <div class="box img"> <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'full', array( 'itemprop' => 'image' ) ); } ?> </div> </div> </div> <?php }
为什么之前的判断失效?
init钩子在WordPress初始化阶段就触发,此时还未处理当前请求的页面查询,$wp_query对象未完成初始化,is_page()、get_post_type()这类依赖页面查询结果的函数无法获取正确值,导致判断条件不生效。template_redirect钩子在WP完成主查询、确定要加载的模板之后触发,此时所有页面判断函数都能正常工作,你的条件判断会准确生效。
内容的提问来源于stack exchange,提问作者Schalk Joubert
相关产品推荐
相关产品推荐

