【问题标题】:Override a Wordpress parent theme function覆盖 Wordpress 父主题功能
【发布时间】:2015-07-27 01:33:48
【问题描述】:

我正在创建 flowmaster 主题的子主题。我在覆盖父函数时遇到问题。 该功能存在于父主题中:

add_filter('loop_shop_columns', 'pt_loop_shop_columns');
function pt_loop_shop_columns(){
    if ( 'layout-one-col' == pt_show_layout() ) return 4;
    else return 3;
}

我在子主题中添加了一个功能

if ( ! function_exists( 'pt_loop_shop_columns' ) ) :
function pt_loop_shop_columns(){
    global $wp_query;
    if ( 'layout-one-col' == pt_show_layout() ) return 4;
    else return 4;
}
endif;
add_filter('loop_shop_columns', 'pt_loop_shop_columns');

收到此错误:

致命错误:无法重新声明 pt_loop_shop_columns()(以前 宣布于 C:\xampp\htdocs\futuratab\wp-content\themes\flowmaster-child\functions.php:44) 在 C:\xampp\htdocs\futuratab\wp-content\themes\flowmaster\woofunctions.php 在第 9 行

请帮忙。谢谢

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    先执行子主题的功能,然后执行父主题的功能。使用function_exists 进行检查应该在父主题中完成。

    要克服这个问题,您可以删除父主题的挂钩并将您的自定义函数挂钩到相同的过滤器。

    remove_filter('loop_shop_columns', 'pt_loop_shop_columns');
    
    add_filter('loop_shop_columns', 'custom_pt_loop_shop_columns');
    
    function custom_pt_loop_shop_columns(){
        global $wp_query;
        if ( 'layout-one-col' == pt_show_layout() ) return 4;
        else return 4;
    }
    

    【讨论】:

    • 谢谢您的回复。function_exists 没有添加到父主题中。在子主题函数中添加此代码错误消失了。但它没有返回 4 行中的项目。它仍然是 3 行中的项目。
    • 然后尝试降低优先级,add_filter('loop_shop_columns', 'custom_pt_loop_shop_columns', 20);
    • 为什么是 20 ??它与 20 一起使用。我可以添加任何其他尝试低于 11 但不能在 11 以上工作的数字。
    • 默认优先级为10。您可以分配大于 10 的数字。
    • 感谢您的帮助。
    【解决方案2】:

    你不能在 PHP 中重新定义一个函数,但是你可以解开旧函数的钩子并用不同的名字钩子新函数。比如:

    remove_filter('loop_shop_columns', 'pt_loop_shop_columns');
    add_filter('loop_shop_columns', 'pt_loop_shop_columns_2');
    

    【讨论】:

      【解决方案3】:

      你可以在你的孩子主题上试试这个

      function pt_loop_shop_columns() {
      
      //NEW CODE IN HERE///////////////////////////////
      
      return apply_filters('pt_loop_shop_columns', $link, $id);
      }
      
      add_filter('attachment_link', 'pt_loop_shop_columns');
      

      你可以在现有函数上使用钩子

      function pt_loop_shop_columns() {
      //code goes here
      }
      
      $hook = 'get_options'; // the function name you're filtering
      add_filter( $hook, 'pt_loop_shop_columns' );
      

      最后一个方法是

       function remove_thematic_actions() {
      remove_action('thematic_header','thematic_blogtitle',3);
      }
      // Call 'remove_thematic_actions' during WP initialization
      add_action('init','remove_thematic_actions');
      
      // Add our custom function to the 'thematic_header' phase
      add_action('thematic_header','fancy_theme_blogtitle', 3);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        • 2015-08-08
        • 2013-11-10
        • 1970-01-01
        • 2019-02-28
        相关资源
        最近更新 更多