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

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

2023-06-11 / 535阅

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

  1. 在主题的functions.php文件中添加以下代码,创建自定义字段。
  1. function wpdocs_theme_customizer_init() {
  2. // Define a new section for custom fields
  3. $wp_customize->add_section( 'custom_fields', array(
  4. 'title' => __( 'Custom Fields', 'textdomain' ),
  5. 'description' => __( 'Add custom fields for your theme.', 'textdomain' ),
  6. 'priority' => 160,
  7. ) );
  8. // Define the custom fields
  9. $wp_customize->add_setting( 'custom_field_one', array(
  10. 'default' => '',
  11. ) );
  12. $wp_customize->add_control( 'custom_field_one_control', array(
  13. 'label' => __( 'Custom Field One', 'textdomain' ),
  14. 'section' => 'custom_fields',
  15. 'settings' => 'custom_field_one',
  16. 'type' => 'text',
  17. ) );
  18. }
  19. add_action( 'customize_register', 'wpdocs_theme_customizer_init' );
  1. 在文章或页面中添加自定义字段的值。

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

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

  1. 调用自定义字段。

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

  1. $custom_field_one = get_post_meta( get_the_ID(), 'custom_field_one', true );
  2. if ( $custom_field_one ) {
  3. echo '<p>' . esc_html( $custom_field_one ) . '</p>';
  4. }

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

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

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

大家谈论
    我的见解


    目录