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

Ale*_*ena 2 wordpress wordpress-theming parent-child

我想重写子主题中的函数,该函数在父主题的类中定义。

这是示例代码:

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

}
Run Code Online (Sandbox Code Playgroud)

附加信息:

B类扩展了C类,C类是定义的根类add_ajax

我尝试过的:

  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
    }
    
    Run Code Online (Sandbox Code Playgroud)

有什么帮助请...

Atl*_*dal 5

您只需两个简单的步骤即可覆盖该类的方法。

就是这样:

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

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

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