如何阅读,如果一个复选框被选中在PHP?


当前回答

我已经把它固定成一个带有复选框的PHP表单

$categories = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false]); Foreach ($categories为$ categororie) { Echo "<input type="checkbox" value="$ categororie ->term_taxonomy_id" name="catselected[]"> $ categororie ->slug"; }

这样我把它添加到Woocommerce表。 wp_set_post_terms($product_id, $_POST['catselected'], 'product_cat');

其他回答

filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)

一个极简的布尔检查开关位置保留

<?php

$checked = ($_POST['foo'] == ' checked');

?>

<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>

当使用复选框作为数组时:

<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">

你应该使用in_array():

if(in_array('Orange', $_POST['food'])){
  echo 'Orange was checked!';
}

记得先检查数组是否被设置,例如:

if(isset($_POST['food']) && in_array(...

Wordpress有checked()函数。 参考:https://developer.wordpress.org/reference/functions/checked/

checked( mixed $checked, mixed $current = true, bool $echo = true )

描述 比较前两个参数,如果相同则标记为选中

参数 美元的检查 (混合)(必选)要比较的值之一

当前美元 (混合)(可选)(true)如果不是true,要比较的另一个值 缺省值:true

美元的回声 (可选)是否返回或返回该字符串 缺省值:true

返回#返回 (string) HTML属性或空字符串

让你的html复选框将是这样的

<input type="checkbox" name="check1">

提交表单后,你需要检查

if (isset($_POST['check1'])) {

    // Checkbox is selected
} else {

   // Alternate code
}

假设check1应该是复选框的名称。如果你的表单提交方法是GET,那么你需要检查$_GET变量像

if (isset($_GET['check1'])) {

   // Checkbox is selected
}