首页 视频课程 主题开发课程第08章、自定义字段 WordPress全局自定义字段使用方法

WordPress全局自定义字段使用方法

2023-06-11 / 256阅

WordPress全局自定义字段使用方法如下:

  1. 在主题的functions.php文件中添加以下代码,创建自定义字段。
function wpdocs_theme_customizer_init() {
    // Define a new section for custom fields
    $wp_customize->add_section( 'custom_fields', array(
        'title' => __( 'Custom Fields', 'textdomain' ),
        'description' => __( 'Add custom fields for your theme.', 'textdomain' ),
        'priority' => 160,
    ) );

    // Define the custom fields
    $wp_customize->add_setting( 'custom_field_one', array(
        'default' => '',
    ) );

    $wp_customize->add_control( 'custom_field_one_control', array(
        'label' => __( 'Custom Field One', 'textdomain' ),
        'section' => 'custom_fields',
        'settings' => 'custom_field_one',
        'type' => 'text',
    ) );
}
add_action( 'customize_register', 'wpdocs_theme_customizer_init' ); 
  1. 在文章或页面中添加自定义字段的值。

可以在文章或页面中编辑添加自定义字段,方法为“编辑文章/页面”→“右上角点击‘选项’”→“向下滚动鼠标查找‘自定义字段’”→“添加字段名称和值”。

例如,自定义字段名称为“custom_field_one”,值为“WordPress Global Custom Fields Usage”。

  1. 调用自定义字段。

可以在文章或页面的模板文件(single.php或page.php)中使用以下代码调用自定义字段。

$custom_field_one = get_post_meta( get_the_ID(), 'custom_field_one', true );

if ( $custom_field_one ) {
    echo '<p>' . esc_html( $custom_field_one ) . '</p>';
} 

这段代码会将自定义字段的值输出到页面上。

以上就是WordPress全局自定义字段使用方法的介绍,希望对你有帮助。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录