在WordPress主题中使用自定义函数,你需要遵循以下步骤:

创建一个子主题:为了避免在更新主题时丢失自定义函数,建议创建一个子主题。在主题文件夹中创建一个新文件夹,例如“wodepress_child_theme”,并在其中创建一个名为“style.css”的样式表文件。在此文件中,添加以下代码以指定父主题:

/*
Theme Name: WordPress Child Theme
Theme URI: http://wodepress.com
Description: WordPress child theme of WordPress
Author: Your Name
Author URI: http://wodepress.com
Template: WordPress
Version: 1.0.0
Text Domain: WordPress-child-theme
*/

创建functions.php文件:在子主题文件夹中创建一个名为“functions.php”的文件。如果你已经有一个functions.php文件,可以在其中添加自定义函数。

编写自定义函数:在functions.php文件中,编写你的自定义函数。例如,创建一个函数来显示文章的阅读时间:

function reading_time() {
    $content = get_post_field( 'post_content', get_the_ID() );
    $word_count = str_word_count( strip_tags( $content ) );
    $reading_time = ceil( $word_count / 200 );

    if ( $reading_time < 1 ) {
        $reading_time = 1;
    }

    return $reading_time;
}

在主题中调用自定义函数:在需要显示阅读时间的地方,调用你刚刚创建的函数。例如,在single.php文件中,你可以添加以下代码:

echo '阅读时间:' . reading_time() . '分钟';

使用钩子:如果你想在特定的WordPress动作或过滤器上调用自定义函数,可以使用add_action()和add_filter()函数。例如,在functions.php文件中添加以下代码:

add_action( 'wp_head', 'my_custom_function' );

function my_custom_function() {
    // Insert custom code within the<head>tag
    echo '<meta name="author" content="Your Name">';
}

通过遵循这些步骤,你可以在WordPress主题中轻松地使用自定义函数。