Код: Выделить всё
npt_gift_card
Вот мой текущий код:< /p>
Код: Выделить всё
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Plugin Name: Gutschein Product Type Plugin
* Description: Adds a new product type "Gift Card" (Gutschein).
* Version: 1.0
* Author: My Name
*/
// Step 1: Register the product type
add_action( 'init', 'register_gift_card_product_type' );
function register_gift_card_product_type() {
class WC_Product_Gift_Card extends WC_Product {
public function __construct( $product ) {
$this->product_type = 'npt_gift_card';
parent::__construct( $product );
}
}
}
// Step 2: Add the product type to the selector
add_filter( 'product_type_selector', 'add_gift_card_product_type' );
function add_gift_card_product_type( $types ) {
$types['npt_gift_card'] = __( 'Gift Card', 'woocommerce' );
return $types;
}
// Step 3: Add custom fields in admin
add_action( 'woocommerce_product_options_general_product_data', 'gift_card_custom_fields' );
function gift_card_custom_fields() {
echo '';
woocommerce_wp_text_input( array(
'id' => '_gift_card_value',
'label' => __( 'Gift Card Value', 'woocommerce' ),
'description' => __( 'Enter the value of the gift card (e.g., 50)', 'woocommerce' ),
'type' => 'number',
'desc_tip' => true,
) );
echo '';
}
// Step 4: Save custom fields
add_action( 'woocommerce_process_product_meta', 'save_gift_card_custom_fields' );
function save_gift_card_custom_fields( $post_id ) {
$gift_card_value = isset( $_POST['_gift_card_value'] ) ? sanitize_text_field( $_POST['_gift_card_value'] ) : '';
update_post_meta( $post_id, '_gift_card_value', $gift_card_value );
}
// Step 5: Display custom fields on the product page
add_action( 'woocommerce_single_product_summary', 'display_gift_card_value', 25 );
function display_gift_card_value() {
global $product;
if ( $product->get_type() === 'npt_gift_card' ) {
$gift_card_value = get_post_meta( $product->get_id(), '_gift_card_value', true );
if ( ! empty( $gift_card_value ) ) {
echo '' . __( 'Gift Card Value: ', 'woocommerce' ) . wc_price( $gift_card_value ) . '
';
}
}
}
- Подарочная карта типа продукта не работает. не отображается в раскрывающемся списке при создании или редактировании продуктов в администраторе WooCommerce.
- Настраиваемое поле для стоимости подарочной карты не отображается в параметрах продукта.
Среда:
- WordPress 6.7.1
- WooCommerce 9.4.3
- PHP 8.2
Подробнее здесь: https://stackoverflow.com/questions/792 ... tom-fields