WordPress:在子主题中覆盖父主题 class 功能

WordPress: Override parent theme class function in child theme

我想覆盖子主题中的函数,它在父主题的 class 中定义。

示例代码如下:

class A extends B{
   function __construct(){
      $this->add_ajax('sync_post_data', 'need_to_override');
   }
   //other functions
   function need_to_override(){
      //function code
   }

}

附加信息:

Class B extends Class C and Class C is the root class where add_ajax is defined.

我试过的:

  1. 由于函数不可插入,所以我不能直接在子主题中覆盖函数。
  2. 其次,我尝试删除 ajax 操作并添加我的自定义操作。它抛出 500 个内部服务器错误。

    remove_action( 'wp_ajax_sync_post_data', 'need_to_override' );
    add_action( 'wp_ajax_sync_post_data', 'custom_function' );
    
    function custom_function(){
       //function code with my custom modification
    }
    

任何帮助请...

您只需两个简单的步骤即可重写 class 的方法。

方法如下:

  1. 打开子主题functions.php
  2. 像这样创建新的 class:

    add_action( 'after_setup_theme', function() {
    
    
       class D extends A{
    
          function need_to_override(){
             //original function code with your custom modifications
          }
    
       }
    
       new D();
    });
    

PS:它会起作用,但我不确定它是否是最好的方法!