在 wordpress 的子主题 functions.php 中禁用主题功能

Disable a theme function in from a child theme functions.php in wordpress

我在 wordpress 中遇到了我的主题问题,它在我的主题上显示了它自己的 og:meta 描述,因此由于 all in one seo 插件,它被复制了。

我想从主题中禁用那些,但我不知道如何,所以我设法在 php 文件中找到触发它显示在网站上的功能,但我没有知道如何从 functions.php 或我的子主题中禁用它,因此更新时它不会被覆盖。有问题的功能如下

// Open Graph Meta
function aurum_wp_head_open_graph_meta() {
 global $post;

 // Only show if open graph meta is allowed
 if ( ! apply_filters( 'aurum_open_graph_meta', true ) ) {
  return;
 }

 // Do not show open graph meta on single posts
 if ( ! is_singular() ) {
  return;
 }

 $image = '';

 if ( has_post_thumbnail( $post->ID ) ) {
  $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'original' );
  $image = esc_attr( $featured_image[0] );
 }

 ?>

 <meta property="og:type" content="article"/>
 <meta property="og:title" content="<?php echo esc_attr( get_the_title() ); ?>"/>
 <meta property="og:url" content="<?php echo esc_url( get_permalink() ); ?>"/>
 <meta property="og:site_name" content="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>"/>
 <meta property="og:description" content="<?php echo esc_attr( get_the_excerpt() ); ?>"/>

 <?php if ( '' != $image ) : ?>
 <meta property="og:image" content="<?php echo $image; ?>"/>
 <?php endif;
}

add_action( 'wp_head', 'aurum_wp_head_open_graph_meta', 5 );

非常感谢。

这个函数实际上有一个内置的方法来提前短路和return。如果 false 的值被传递给过滤器 aurum_open_graph_meta if will return 在创建任何输出之前。

add_filter( 'aurum_open_graph_meta',  '__return_false' );

您可以在此处阅读有关特殊 __return_false() 功能的信息:https://codex.wordpress.org/Function_Reference/_return_false

如果此函数没有早期的 return 标志,则停止执行的另一种方法是删除函数创建的操作。这将是一种更通用的方法,可以应用于在 WordPress 中任何地方注册的大多数操作。

添加您自己的操作在添加要删除的操作之后但在执行之前

在这种情况下,您可以使用 init 挂钩来实现。在您的操作函数中调用 remove_action() 并提供您要删除的详细信息或挂钩。

add_action( 'init', 'remove_my_action' );
function remove_my_action(){
      remove_action( 'wp_head', 'aurum_wp_head_open_graph_meta', 5 );
}

请注意,需要在添加操作的同一 $priority 上删除该操作(在本例中为“5”)。尝试将以上代码添加到您子主题的 functions.php 文件中,看看它是否删除了该操作。

如果您只支持 php>5.3,那么您可以使用 anonymous function:

清理该代码
add_action( 'init', function() { 
    remove_action( 'wp_head', 'aurum_wp_head_open_graph_meta', 5 );
}

关于 WordPress 中 adding/removing 操作的一些补充阅读:https://codex.wordpress.org/Function_Reference/remove_action