Wordpress模板和类方法

时间:2015-12-06 09:14:56

标签: php wordpress templates

是否可以从自定义类加载模板文件(例如使用page_template挂钩)并且能够在模板中调用该类实例的方法?我知道我可以从模板中调用类似the_title()的方法,但我无法弄清楚是否可以直接从模板调用自定义类方法,即使该模板已经通过该类加载。

换句话说,是否可以获取下面的模板文件来调用公共方法callSomeClassMethodHere(),就像调用the_title()一样?我开始认为这是不可能的。

CustomPluginTemplate.php

<?php get_header(); ?>
<main id="main" class="site-main" role="main">
    <div>
        <p><?php callSomeClassMethodHere() ?></p>
    </div>
</main>
<?php get_footer(); ?>

CustomPlugin.php

<?php

/*
Plugin Name: My Custom Plugin
Description: This is a test plugin
Version: 0.0.1
*/

class CustomPlugin extends \WP_Widget {
    public function __construct() {
        parent::__construct(
            'CustomPlugin', // ID
            __('Custom Plugin', 'text_domain'), // Name
            array( 'description' => __( 'This is a custom plugin', 'text_domain' )) // Description
        );

        add_action('init', array($this, 'init'), 10, 0);
        add_filter('query_vars', array($this, 'query_vars'));
        add_action('page_template', array($this, 'page_template'));
    }

    public function init() {
        add_rewrite_rule(
            '^custom-page/([^/]*)',
            'index.php?page_id=2&custom_id=$matches[1]',
            'top'
        );

    }

    public function query_vars($query_vars) {
        $query_vars[] = 'custom_id';

        return $query_vars;
    }

    public function page_template($path = '') {
        $path = dirname(__FILE__) . '/CustomPluginTemplate.php';

        return $path;
    }
}

add_action('widgets_init', function () { register_widget('CustomPlugin'); });

1 个答案:

答案 0 :(得分:0)

您可以直接调用类方法

$myPlugin = new CustomPlugin();
$myPlugin->page_template('your_path');

在这种情况下,在声明类时使用钩子,然后你必须修改一个方法来返回一个模板。您可以使用load_template()功能或get_template_part()