Trong hướng dẫn này, tôi sẽ giải thích cho bạn cách hiển thị hoặc ẩn một trường tùy thuộc vào giá trị của trường khác trong metabox WordPress đơn giản.

Để biết thêm chi tiết, bạn cũng có thể xem hướng dẫn của tôi về Metabox WordPress .
Để tạo một hộp meta với logic có điều kiện cho các trường của nó, chúng ta chỉ cần thực hiện hai bước. Bước đầu tiên là dán mã sau vào functions.php
tệp chủ đề hiện tại của bạn hoặc vào một plugin tùy chỉnh.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<?php add_action( 'add_meta_boxes', 'hwp_add_product_metabox' ); function hwp_add_product_metabox() { add_meta_box( 'hwp_product_metabox', 'Meta Box', 'hwp_callback', 'product', 'normal', 'default' ); } function hwp_callback( $post ) { $product_type = get_post_meta( $post->ID, 'product_type', true ); $items_in_stock = get_post_meta( $post->ID, 'items_in_stock', true ); // you can add a nonce field here as well ?> <table class="form-table"> <tbody> <tr> <th>Product type</th> <td> <p> <label> <input type="radio" name="product_type"<?php checked( $product_type, 'virtual' ) ?> value="virtual"> Virtual </label> </p> <p> <label> <input type="radio" name="product_type"<?php checked( $product_type, 'physical' ) ?> value="physical"> Physical </label> </p> </td> </tr> <tr<?php echo 'physical' !== $product_type ? ' style="display:none"' : '' ?>> <th><label for="items_in_stock">Items in stock</label></th> <td> <input type="number" id="items_in_stock" name="items_in_stock" value="<?php echo absint( $items_in_stock ) ?>" class="small-text"> </td> </tr> </tbody> </table> <?php } add_action( 'save_post', 'hwp_save_product_meta', 10, 2 ); function hwp_save_product_meta( $post_id, $post ) { // you can add nonce, permission and post type validation here update_post_meta( $post_id, 'product_type', sanitize_text_field( $_POST[ 'product_type' ] ) ); update_post_meta( $post_id, 'items_in_stock', absint( $_POST[ 'items_in_stock' ] ) ); } |
Bước thứ 2 – chúng ta cũng phải thêm một số JavaScript, vì vậy trường số sẽ bị ẩn hoặc hiển thị tùy thuộc vào giá trị của các nút radio. Đoạn mã dưới đây:
1 2 3 4 5 6 7 8 9 |
jQuery( function( $ ) { $( 'input[name="product_type"]' ).change( function() { if( 'physical' == $(this).val() ) { $( '#items_in_stock' ).parent().parent().show(); } else { $( '#items_in_stock' ).parent().parent().hide(); } }); } ); |
A/E thích mò mẫm thì làm theo hướng dẫn, thấy hay thì chia sẻ bài viết đến mọi người, có đoạn code hay chia sẻ cho ae cùng tham khảo… Chúc ae thành công!