考虑一下remove_action文档中的这些注释:
- 您可能需要将删除操作的优先级放在添加操作后发生的挂钩上。
- 在添加操作之前,您无法成功删除该操作。
- 您也无法在运行后删除操作。
- 要删除操作,优先级必须与最初添加的功能相匹配。
在您的情况下,我相信其中几个问题(尤其是 #3 和 #4)会导致问题:
首先,你的优先级add_action太高了。通过将其设置得如此高,它会在所有 Yoast操作运行后运行。wp_head相反,挂钩到您要删除的相同操作,但使用非常小的数字,例如 -99999,使其在运行Yoast 操作之前运行。(此外,我已分解为两个函数,以确保它们在正确的时间运行 - 每个动作一个 -wp_head和wpseo_head)。
其次,您的优先级与 Yoast 代码中的优先级不匹配。我已经挖掘了所有 Yoast 代码以找到所有这些操作,并在下面的代码中记录/更正了 - 例如,我可以告诉你metakeywordsYoast 代码中的钩子是 11,所以你的 remove_action (优先级为 40)将不起作用.
最后,Yoast 将这些操作添加到$this(WPSEO_Frontend 类的实例化版本),而不是类方法的静态版本。例如,这意味着remove_action无法根据函数 array( WPSEO_Frontend, head) 找到它们。相反,您需要加载 Yoast 的实例化版本,并将其传递给函数remove_action。
下面记录的代码:
// Remove ONLY the head actions. Permits calling this at a "safe" time
function remove_head_actions() {
// not Yoast, but WP default. Priority is 1
remove_action( 'wp_head', '_wp_render_title_tag', 1 );
// If the plugin isn't installed, don't run this!
if ( ! is_callable( array( 'WPSEO_Frontend', 'get_instance' ) ) ) {
return;
}
// Get the WPSEO_Frontend instantiated class
$yoast = WPSEO_Frontend::get_instance();
// removed your "test" action - no need
// per Yoast code, this is priority 0
remove_action( 'wp_head', array( $yoast, 'front_page_specific_init' ), 0 );
// per Yoast code, this is priority 1
remove_action( 'wp_head', array( $yoast, 'head' ), 1 );
}
function remove_wpseo_head_actions() {
// If the Yoast plugin isn't installed, don't run this
if ( ! is_callable( array( 'WPSEO_Frontend', 'get_instance' ) ) ) {
return;
}
// Get the Yoast instantiated class
$yoast = WPSEO_Frontend::get_instance();
remove_action( 'wpseo_head', array( $yoast, 'head' ), 50 );
// per Yoast code, this is priority 6
remove_action( 'wpseo_head', array( $yoast, 'metadesc' ), 6 );
// per Yoast code, this is priority 10
remove_action( 'wpseo_head', array( $yoast, 'robots' ), 10 );
// per Yoast code, this is priority 11
remove_action( 'wpseo_head', array( $yoast, 'metakeywords' ), 11 );
// per Yoast code, this is priority 20
remove_action( 'wpseo_head', array( $yoast, 'canonical' ), 20 );
// per Yoast code, this is priority 21
remove_action( 'wpseo_head', array( $yoast, 'adjacent_rel_links' ), 21 );
// per Yoast code, this is priority 22
remove_action( 'wpseo_head', array( $yoast, 'publisher' ), 22 );
}
最后注:。
删除 WPSEO_Frontend::head 动作非常重。这将取消您可能不想删除的许多其他内容。
其次,最好修改这些操作的输出,而不是完全删除它们。
例如,
add_action('wpseo_metakeywords', 'your_metakeywords_function');
function your_metakeywords_function( $keywords ) {
// modify the keywords as desired
return $keywords;
}