我正试图通过jquery将一个值传递到wooccommerce的SKU输入字段,该字段是在您单击wp-admin/edit.php?post_type=product
中的快速编辑按钮时动态生成的,但由于某些原因,没有将值粘贴到字段中。
function generateRandomString($length = 10) {
$characters = '0123456789ABCDEFGHIJKMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function quick_edit_sku($product) {
$string = generateRandomString(); // outputs a random string correctly
?>
<script>
jQuery(document).ready(function($) {
$('.editinline').on('click', function(event) {
var sku_val = $("input[name=_sku]").val(); // checks if there is a value
var random = '<?php echo $string ?>';
if (sku_val === '') { // if SKU field is empty than apply random string. Though this doesn't work quite well, only on the second time I click quick edit it returned correct
console.log(random);
$("input[name=_sku]").val(random);
} else {
console.log('Already has value SKU value');
}
});
});
</script>
<?php }
add_filter( 'admin_footer', 'quick_edit_sku' );
按钮+萤火虫http://postimg.org/image/oqdpkhqov/
问题是js很快就会被触发,当你点击"快速编辑"时,wordpress会发送一个Ajax请求来获取快速编辑选项的HTML,所以在最初点击时input[name=_sku]
实际上并不存在。只需在添加值之前添加setTimeout
函数即可:
<script>
jQuery(document).ready(function($) {
$('.editinline').on('click', function(event) {
var sku_val = $("input[name=_sku]").val();
var random = '<?php echo $string ?>';
if (!sku_val) {
console.log(random);
setTimeout(function(){
$("input[name=_sku]").val(random)
}, 100);
} else {
console.log('Already has value SKU value');
}
});
});
</script>
此外,您的检查if (sku_val === '') { ... }
失败。
然而,使用if (!sku_val) { ... }
将起作用。
(根据WP 4.1.1进行测试)