WordPress: Override parent theme class function in child theme

[亡魂溺海] 提交于 2019-12-11 15:35:00

问题


I want to override function in child theme, which is defined inside a class in parent theme.

Here is the sample code:

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

}

Additional Information:

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

What I've tried:

  1. As the function is not pluggable so I can't override function directly in child theme.
  2. Secondly I tried to remove ajax action and add my custom action. It throws 500 internal server error.

    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
    }
    

Any help please...


回答1:


You can just override that method of class in just two simple steps.

Here's how:

  1. Open child theme functions.php
  2. Create new class like this:

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

PS: It will work but I'm not sure if it is the best way or not!



来源:https://stackoverflow.com/questions/53293310/wordpress-override-parent-theme-class-function-in-child-theme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!