Wordpress的核心功能往往都是通过向各种hook添加不同的filter或者action而实现的. 现在, 我们就举举例子.
向我们的主函数latex2html.php
的__construct
函数添加核心功能函数类:
//protected static $instance;
//const l2h_VER='1.0';
public function __construct()
{
# INIT the plugin: Hook your callbacks
// The setting code ...
/**
* The core
*/
require_once( dirname( __FILE__ ).'/includes/core.php' );
/**
* Instantiate do the following things in construct
*/
//add_action( 'wp_head', array( 'l2h_core_function_class', 'l2h_style_adder' ) );
$l2h_core_function = new l2h_core_function_class( );
其中includes/core.php
包含了一个类 l2h_core_function_class
. 然后我们实例化该类. 当然, 一旦在里面定义了相应的函数, 例如这里的l2h_style_adder
, 你也可以通过array( 'l2h_core_function_class', 'l2h_style_adder' )
来添加action
(参考注释掉的一行).
下面, 我们来看类文件includes/core.php
:
if( !class_exists( 'l2h_core_function_class' ) )
{
class l2h_core_function_class
{
// declare some variables
private $options, $preamble, $style;
/**
* The Constructor
*/
public function __construct()
{
$this->options = get_option( 'l2h_options' );
$this->preamble = $this->options['latex_cmd'];
$this->style = $this->options['latex_style'];
// Register actions
add_action( 'wp_head', array( $this, 'l2h_custom_style_adder' ) );
add_filter( 'the_content', array( $this, 'l2h_mathjax_adder' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'l2h_enqueue_style' ) );
}
public function l2h_custom_style_adder( )
{
echo '<style>' . "\n" . $this->options['latex_style'] . "\n</style>\n";
}
public function l2h_mathjax_adder( $content )
{
if( preg_match( '/\\\\\[(.*?)\\\\]/ims', $content ) || preg_match( '/\$(.*?)\$/ims', $content) ){
if( is_single() || (isset( $this->options['single'] ) && !$this->options['single'] ) )
{
add_action( 'wp_footer', array( $this, 'l2h_preamble_adder') );
add_action( 'wp_footer', array( $this, 'l2h_mathjax_single_adder' ) );
}
}
return $content;
}
// The function l2h_preamble_adder
// The function l2h_mathjax_single_adder
public function l2h_enqueue_style( )
{
wp_enqueue_style( 'l2h_style', plugin_dir_url( __FILE__ ) . '../css/latex.css', false, active_deactive_class::l2h_VER , 'screen, print' );
wp_enqueue_style( 'l2h_print_style', plugin_dir_url( __FILE__ ) . '../css/print.css', false, active_deactive_class::l2h_VER, 'print' );
}
}
上面的代码, 首先定义了几个变量. 然后在__construct
函数中赋值. 接着我们添加了各种filter和action, 具体的函数都在后面定义. 从简单的直接返回变量的函数l2h_custom_style_adder
到在函数中传参$content
, 并且调用其他函数(因为给l2h_preamble_adder()
和l2h_mathjax_single_adder()
设置了public属性), 最后, 我演示了如何添加自定义css(完全类似添加js, 只需查看wp_enqueue_script
), 而且, 作为例子, 我们还传入了active_deactive_class
中定义的类常量l2h_VER
, 它的值是当前版本号.
网友评论