如何使用 wordpress 元框中的复选框值


How do I use a checkbox value from a wordpress meta box?

我正在尝试在wordpress中使用自定义元框。我目前的目标是创建一个带有复选框的元框,我可以将其用作打开某些内容的开关。我一直在网络上搜索,试图拼凑出一些有用的东西,到目前为止,我已经足够远,我可以生成一个带有复选框的元框,但由于某种原因,选中的值没有转移到循环中。当我尝试输出数组以查看是否可以从中获取任何内容时,它是空的。我已经看了很多东西,并尝试了几个元框创建脚本,但我无法让其中任何一个工作。这种方法看起来是最有前途的,但现在我卡住了。我在这里缺少什么重要的东西吗?就好像数据没有被保存一样。代码包括如下:

元框函数。位于功能.php:

// Checkbox Meta
add_action("admin_init", "checkbox_init");
function checkbox_init(){
add_meta_box("checkbox", "Checkbox", "checkbox", "post", "normal", "high");
}
function checkbox(){
global $post;
$custom = get_post_custom($post->ID);
$field_id = $custom["field_id"][0];
echo '<label>Check for yes</label>';
$field_id_value = get_post_meta($post->ID, 'field_id', true);
if($field_id_value == "yes") {
    $field_id_checked = 'checked="checked"';
}
echo ' <input type="checkbox" name="field_id" value="yes" '.$field_id_checked.' />';
}
// Save Meta Details
add_action('save_post', 'save_details');
function save_details(){
  global $post;
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
     return $post->ID;
  }
update_post_meta($post->ID, "field_id", $_POST["field_id"]);
}

选中复选框时用于输出内容的代码。这也位于函数.php中。该函数在循环中使用。

function custom_content() {
    if(isset($_POST['field_id']) && $_POST['field_id'] == 'yes') {
        echo "It works!";
    }
}

将函数上的函数.php更改为

function custom_content($id) {
    $field_id = get_post_meta($id, 'field_id', true);
    if($field_id == yes) {
        echo "It works!";
    }
    else{
        echo 'Not working...';
    }
}

而你的模板,像ff一样在循环中调用它:

custom_content(get_the_ID());