如何允许用户在wordpress页面上添加动态自定义字段?

时间:2018-01-21 23:15:45

标签: php wordpress advanced-custom-fields

我正在尝试使用个人资料页面,用户可以在自定义字段表单上反复添加某些字段。

字段将在UI中表示,如:

Input Field (Name)    |    Input Field (Number)             + (Add new)

因此,当用户点击Add new时,上面的字段会重复,如下所示:

Input Field (Name)    |    Input Field (Number) 
Input Field (Name)    |    Input Field (Number)

我读到自定义字段是我需要的,并尝试将下面的代码块放在我的主题functions.php文件中:

// handle custom meta boxes for the user progile page
add_action('add_meta_boxes', 'register_new_user_field');
function register_new_user_field(){
  global $post;
  if(!empty($post))
  {
    $pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);

    if($pageTemplate == 'page-templates/template-dashboard.php' ){
      add_meta_box(
            'custom-user-post-id',
            'Label',
            'customer_submit_callback',
            'page',
        'normal',
        'high'
        );
    }
  }
}

function customer_submit_callback(){
    // display output to user
        echo '<label for="custom-user-post-id"><p>Custom Title</p></label>';
    echo '<input name="custom-user-post-id" id="custom-user-post-id" cols="62" rows="5" ></input>';
    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
}

function wpdocs_save_meta_box($post_id){
    // Save logic
    // // if our nonce isn't there, or we can't verify it, bail
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    return;
  }
  if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

    if( isset( $_POST['custom-user-post-id'] ) )
      update_post_meta( $post_id, 'custom-user-post-id', $_POST['custom-user-post-id'] );
}
add_action( 'save_post', 'wpdocs_save_meta_box' );

但是,当我转到用户个人资料页面时,这些字段不存在。任何帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:0)

所以你要做的就是在页面上添加用户可以随意编辑的部分。

  • 步骤1.下载高级自定义字段
  • 步骤2.创建字段组
  • 步骤3.单击添加字段
  • 步骤4.将字段标签设置为:Custom Post ID
  • 步骤5.将字段名称设置为custom_post_id
  • 步骤6.选择文字
  • 步骤7.向下滚动到选项
  • 步骤8.从位置下拉列表中选择“侧面”
  • 步骤9.单击“保存/发布/更新”

要限制元框出现的位置,请在位置字段中选择:

页面模板&gt;是等于&gt;您的模板

现在,该框将显示所有页面上的所有其他元数据。

为了使ID真正有用,我假设你会在某处回应它,所以这就是你将如何做到这一点:

<?php the_field('custom_post_id');?>

使用它的实际案例:

<div class="wrapper wrapper-<?php the_field('custom_post_id');?>">

如果用户在管理区域的字段中输入“1”,则会显示:

<div class="wrapper wrapper-1">