【问题标题】:Wordpress is_single call from plugin class constructor来自插件类构造函数的 Wordpress is_single 调用
【发布时间】:2014-01-02 02:02:59
【问题描述】:

大家好,新年快乐。

最近我正在开发一个插件,但我被困在插件类的实例化步骤上。

这是我在主文件中得到的:

<?php

class Filter_Content {

 public function __construct() {
    if( !is_front_page() && !is_home() && !is_single() ) return;
    if( !is_singular( array('post','page') ) ) return;

    add_filter( 'the_content', array(&$this, 'manage_page_content') );
 }


 public function manage_page_content($content) {

    global $post;
    $content_enabled = get_post_meta( $post->ID, 'post_content_enabled', true );

    if( !$content_enabled ) {
        $content = '';
    }

    return $content;
 }

}

$filtercontent = new Filter_Content();

?>

但是,当调用构造方法 is_single()is_home() 时,它们不起作用, 当我将 if 语句移至方法时,它们可以正常工作。 我必须将 if 语句移到构造函数的原因是因为会有更多的方法使用这些语句。

【问题讨论】:

  • 你是什么意思他们“不工作”?它在做什么构成非工作状态?你有错误吗?你能告诉我们错误吗?
  • 嗨 maiorano84,我的意思是没有错误飞行甚至没有线索。我有 wp-config.php 错误调试真的。因此,我所说的不工作是指当我在一个帖子上时,它不会总是抛出真正的错误。
  • 可能是操作顺序的问题。插件是在大多数其他东西之前设置的,此时全局$wp_query 对象可能尚未实例化,以便您有意义地使用is_single()is_singular()。尝试在 init 操作回调中实例化 Filter_Content
  • 您好 maiorano84 非常感谢您花时间欣赏它。我尝试了add_action( 'init', array( 'Filter_Content', 'init' ) ); 并插入了静态方法static public function init() { $self = __CLASS__; new $self; } 它仍然是相同的,我应该挂钩哪个动作?我认为在 init 中它也不起作用。
  • 当您查看单个帖子时,您正在查看的帖子类型是什么?如果您没有查看 post_type 'post' 或 'page' 的单个帖子,您的 is_singular() 会阻止过滤器执行,因此这也可能是一个问题。尝试将exit('DEBUGGING'); 放在您的过滤器调用上方,看看“调试”一词出现在哪里(如果有的话)

标签: php wordpress


【解决方案1】:

试一试,在代码中添加注释

public function __construct() {

    // Plugins are loaded before themes so you need to fire this when theme template is loading EG wp_head hook
    add_action( 'wp_head', array(&$this, 'filter_check') );
 }


 public function filter_check() {
    if( !is_front_page() && !is_home() && !is_single() ) return;
    if( !is_singular( array('post','page') ) ) return;

    add_filter( 'the_content', array(&$this, 'manage_page_content') );
 }

【讨论】:

  • 在我也添加了标题过滤器之后,现在使用您的方法过滤标题影响 wp_nav 内容,它将它们全部擦除,其概念与过滤内容相同。你知道什么可能导致这个吗?
  • 如果它与您的 manage_page_content 方法相同,请先检查其帖子类型是否为帖子 if($post->post_type == 'post') { // 您的代码 }
  • 没有太大帮助。还是一样,我还是把它当作一个问题来问吧。
猜你喜欢
  • 2012-01-30
  • 1970-01-01
  • 2012-07-28
  • 1970-01-01
  • 1970-01-01
  • 2014-01-29
  • 2016-04-06
  • 2012-01-28
  • 2015-03-15
相关资源
最近更新 更多