【问题标题】:WordPress: Store data from input fields to database and than retrieve itWordPress:将数据从输入字段存储到数据库,然后检索它
【发布时间】:2014-09-23 07:58:31
【问题描述】:

我的输入字段的名称如下:child1child[2]child[3] 等。用户可以根据需要添加任意数量的字段,使用 jquery 处理并动态添加名称末尾带有 [n] 的输入字段。

现在我需要将这些数据存储到我正在使用的 WordPress 插件中的数据库中。然后检索此数据以将其显示在网站上,并在用户编辑数据的管理页面中添加这些字段。

我知道如何在 WordPress 的数据库中存储一个字段,例如 child,它会是这样的:

<?php $child = get_post_meta( $post->ID, 'child', true ); ?>

<?php
function save_child_data( $post_id ) {

  // Check if exists
  if(! isset($_POST['child'])){return;}

  // Sanitize
  $child_data = sanitize_text_field( $_POST['child'] );

  // Store data
  update_post_meta( $post_id, 'child', $child_data);

}
add_action( 'save_post', 'save_child_data' );
?>

<!-- Field in admin -->
<input type="text" name="child" id="child" value="<?php echo esc_attr($child); ?>">

<!-- Front office -->
<div>Child: <?php echo get_post_meta( $post->ID, 'child', true ); ?></div>

所以我的问题是如何像 child[n] 一样处理这个数组?

或者另一个问题,最好只使用 child1child2child3 并将其作为常规输入字段处理?

所以你明白我在这里动态添加块的意思是一个 jsfiddle 链接:http://jsfiddle.net/alexchizhov/LC2K6/

【问题讨论】:

  • 使用序列化(我建议json)并将其全部存储在一个字段中

标签: php jquery arrays database wordpress


【解决方案1】:

将其作为 JSON 或序列化字符串存储在一个字段中。

http://ch1.php.net/manual/en/function.json-encode.php

http://ch1.php.net/manual/en/function.serialize.php

【讨论】:

  • 我以后可以分离这些数据以逐个检索它吗?
  • 是的。使用 json_decode() 或 unserialize() 您可以取回数组并使用任何循环(例如 foreach())一一获取它们。
  • 我应该如何在 wordpress 中将它与 update_post_meta 一起使用?
  • 好吧,你可以把 json 或者序列化的字符串扔进去。 update_post_meta( $post_id, 'child', serialize($child_data));codex.wordpress.org/Function_Reference/update_post_meta
  • 实际上,用 serialize() 忘记这一点。如果您传递一个数组,update_post_meta 已经这样做了。您只需要将其反序列化回数组。 codex.wordpress.org/Function_Reference/get_post_meta
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-16
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
  • 2016-10-13
相关资源
最近更新 更多