【问题标题】:Wordpress get custom meta box checkbox checkedWordpress 选中自定义元框复选框
【发布时间】:2014-10-10 13:32:35
【问题描述】:

我有一个带有自定义元框的 wordpress 自定义帖子类型。 使用元框,我可以保存 3 个复选框。但是如何从主题中的这些复选框中获取数据?

这是我的功能

function social_services( $post )
{
    // Get post meta value using the key from our save function in the second paramater.
    $custom = get_post_meta($post->ID, '_social_services', true);

    ?>
        <input type="checkbox" id="social_services_soundcloud" name="social_services[]" value="soundcloud" <?php echo (in_array('soundcloud', $custom)) ? 'checked="checked"' : ''; ?>>
        <label for="social_services_soundcloud"></label>Soundcloud<br>

        <input type="checkbox" id="social_services_facebook" name="social_services[]" value="facebook" <?php echo (in_array('facebook', $custom)) ? 'checked="checked"' : ''; ?>>
        <label for="social_services_facebook"></label>Facebook<br>

        <input type="checkbox" id="social_services_twitter" name="social_services[]" value="twitter" <?php echo (in_array('twitter', $custom)) ? 'checked="checked"' : ''; ?>>
        <label for="social_services_twitter"></label>Twitter<br>
    <?php
}

function save_extra_fields(){
  global $post;

    if(isset( $_POST['social_services'] ))
    {
        $custom = $_POST['social_services'];
        $old_meta = get_post_meta($post->ID, '_social_services', true);
        // Update post meta
        if(!empty($old_meta)){
            update_post_meta($post->ID, '_social_services', $custom);
        } else {
            add_post_meta($post->ID, '_social_services', $custom, true);
        }
    }
  // update_post_meta($post->ID, "producers", $_POST["producers"]);
}
add_action( 'save_post', 'save_extra_fields' );

编辑:我用这个修复了它:

if (in_array('soundcloud', get_post_meta($post->ID, '_social_services', true)) == true) {
  // Show the content here
  echo "soundcloud";
}

【问题讨论】:

  • 元值保存到数据库是否正常?您可以通过以下方式单独访问它们:&lt;?php $meta_values = get_post_meta( $post_id, $key, $single ); ?&gt;
  • 保存很好,我也看到切换页面时复选框仍然处于选中状态。
  • 为什么不能使用保存元键值的$custom 变量编写条件?比如:if ($custom) { // Do Something }
  • 我用这个修复了它:if (in_array('soundcloud', get_post_meta($post-&gt;ID, '_social_services', true)) == true) { // Show the content here echo "soundcloud"; }
  • 你可以去掉结尾== true来简化事情。将您的发现添加为答案,而不是编辑!我会投票。很好的解决问题。

标签: php wordpress meta-boxes


【解决方案1】:

我用这个修复了它:

if (in_array('soundcloud', get_post_meta($post->ID, '_social_services', true)) == true) {
  // Show the content here
  echo "soundcloud";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    相关资源
    最近更新 更多