在子主题中添加到functions.php无效

时间:2018-12-13 21:35:31

标签: php wordpress function

我只是想翻译我博客上的一些文本,而恰好在functions.php中。我正在使用一个带有其自己的functions.php的子主题,其中已经从原始functions.php中添加了一些修改后的代码,而没有任何问题。现在,例如,我在原始functions.php中有以下代码:

/**
 * ----------------------------------------------------------------------------------------
 * Custom Search Form
 * ----------------------------------------------------------------------------------------
 */

function infinity_search_form( $value = false ) {
    $placeholder = esc_html__( 'Search...', 'flexblog');
    if ( $value === true ) {
        $placeholder = esc_html__('Type and hit Enter...', 'flexblog');
    }

    $form  = '<form method="get" action="'. esc_url( home_url( '/' ) ) .'" class="infinity-search" >';
        $form .= '<input id="s" class="search_input" type="text" name="s" placeholder="'. $placeholder .'">';
        $form .= '<button type="submit" class="submit button" name="submit" ><i class="fa fa-search" ></i></button>';
    $form .= '</form>';

    return $form;
}

add_filter( 'get_search_form', 'infinity_search_form' );

我要更改的只是“键入并按Enter ...”。我翻译文本,然后将所有内容复制并粘贴到子主题的functions.php中,就像我在此处所做的一样(但使用翻译后的文本)。文本没有在博客上翻译后显示(显示相同),并且后端(WP仪表板)完全损坏(它表示functions.php中存在一些错误-原始错误,即使未触及-在XXX行上,位于我在子主题的functions.php中修改的原始代码所在的位置)。

如果我只替换原始functions.php中的文本,它就可以正常工作。但是出于明显的原因,我想使用子主题中的functions.php。

就像我提到的那样,我已经在子主题的functions.php中添加了一些代码,并且我以相同的方式完成了工作,将其复制到整个主题并将其添加到子主题,编辑需要编辑的内容,然后而已。但这一次它不起作用。

有人知道我在做什么错吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

根据函数在父主题中的编写方式,您当然可以覆盖父函数。在父functions.php文件中,它是可插入函数吗(看起来像这样)?

if ( ! function_exists( 'infinity_search_form' ) ) {
    function infinity_search_form( $value = false ) {

如果出现这种情况,则只需在子主题functions.php文件中声明该函数的新副本。

如果不是这样,则该函数不可插入,您将不得不以其他方式对其进行初始化。最好的选择是在父声明之后声明它(请参见下面的示例):

function infinity_search_form( $value = false ) {
    $placeholder = esc_html__( 'Search...', 'flexblog');
    if ( $value === true ) {
        $placeholder = esc_html__('Type and hit Enter...', 'flexblog');
    }

    $form  = '<form method="get" action="'. esc_url( home_url( '/' ) ) .'" class="infinity-search" >';
    $form .= '<input id="s" class="search_input" type="text" name="s" placeholder="'. $placeholder .'">';
    $form .= '<button type="submit" class="submit button" name="submit" ><i class="fa fa-search" ></i></button>';
    $form .= '</form>';

    return $form;
}
add_action( 'init', 'infinity_search_form', *A NUMBER LARGER THAN THE PARENT DECLARATION*);

以下是WordPress Codex的部分,可能会有所帮助: https://codex.wordpress.org/Child_Themes#Using_functions.php

,这是一个教程指南,可能会对其进行详细说明: https://code.tutsplus.com/tutorials/a-guide-to-overriding-parent-theme-functions-in-your-child-theme--cms-22623

---更新2018-12-17 --- 如果父主题不支持重新声明该方法,则您可能必须尝试以下两种解决方案之一:

1)尝试删除父函数,然后在子主题functions.php文件中重新声明它: https://wordpress.stackexchange.com/questions/273941/how-to-override-parent-theme-function-through-the-child-theme#answer-273955

2)遵循ArtisticPhoenix的说明,并创建自己的函数,您可以自己调用该函数。

相关问题