三分钟热度教程:WordPress插件开发之同一个回调函数挂到不同的钩子

追格官方小助手/ 2022年11月24日/ WordPress/ 浏览 974

因为,我只能保持三分钟热度,所以,知识点一定要在三分钟之内讲完……


在 WordPress 插件/主题开发中,总是有各种各样的需求,代码也会改来改去。有时候,需要把同一个回调函数挂到不同的钩子上,这样做的初始原因大都是为了避免重复代码。


例如:


function wporg_modify_content( $content ) {
	return 'www.zhuige.com : ' . $content;
}

add_filter( 'the_content', 'wporg_modify_content' );
add_filter( 'the_excerpt', 'wporg_modify_content' );


后来,需求变了,要求文章内容前加【追格】,摘要前加【www.zhuige.com】。怎么办呢?如果能在回调函数中区分当前是哪个钩子就好了!


使用 current_action / current_filter 函数,就可以轻松区分!如下:


function wporg_modify_content( $content ) {
	switch ( current_filter() ) {
		case 'the_content':
			$content = '【追格】' . $content;
			break;
		case 'the_excerpt':
			$content = '【www.zhuige.com】' . $content;
			break;
	}
	return $content;
}

add_filter( 'the_content', 'wporg_modify_content' );
add_filter( 'the_excerpt', 'wporg_modify_content' );


完m解决!


不过…… 等等,下面的方法,是不是更好一些?


function wporg_modify_content( $content ) {
	return  '【追格】' . $content;
}
add_filter( 'the_content', 'wporg_modify_content' );

function wporg_modify_excerpt( $content ) {
	return  '【www.zhuige.com】' . $content;
}
add_filter( 'the_excerpt', 'wporg_modify_excerpt' );


发表评论

暂无评论,抢个沙发...

客服 工单