Joe*_*tie 2 php wordpress attributes product woocommerce
我正在尝试在 woocommerce 中创建一个下拉列表框,但用数据库中的数据填充它。
我的大部分代码都在工作,但填充列表框的部分正在杀死我。这是我到目前为止。
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' ); // Display Extra Fields on General Tab Section
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' ); // Save Fields
function woo_add_custom_general_fields() {
global $woocommerce, $post, $product;
echo '<div class="options_group">';
// Select
$options = array(
'hide_empty' => false,
'order' => 'ASC',
'fields' => 'names'
);
$DogBreeds = get_terms('pa_breed', $options);
foreach ($DogBreeds as $key => $value) {
$theArray = "'{$value}' => __( '{$value}' , 'woocommerce' ), ";
}
woocommerce_wp_select(
array(
'id' => '_select',
'label' => __( 'My Select Field', 'woocommerce' ),
'options' => $theArray //this is where I am having trouble
)
);
echo $theArray;
echo '<pre>';
var_dump($DogBreeds);
echo '</pre>';
echo '</div>';
}
// Save Fields
function woo_add_custom_general_fields_save( $post_id ){
// Select
$woocommerce_select = $_POST['_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );
else {
update_post_meta( $post_id, '_select', Null );
}
}
Run Code Online (Sandbox Code Playgroud)
这应该从 WooCommerce 的“属性”部分中提取信息。我创建了一个品种属性,并在其中放了一些狗品种。
任何方向都非常感谢!
我知道阵列上的“选项”部分是完全错误的,但我把它放在那里,所以你会知道我想要完成什么。
我重新审视了你的代码。主要问题出在选择<option>数组中。
您将在代码中看到更改:
// Display Extra Fields on General Tab Section
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
global $post;
// Set HERE the product attribute taxonomy
$taxonomy = 'pa_breed';
// Get the selected value <== <== (updated)
$value = get_post_meta( $post->ID, '_select', true );
if( empty( $value ) ) $value = '';
$dog_breeds = get_terms( $taxonomy, array(
'hide_empty' => false,
'order' => 'ASC',
'fields' => 'names'
) );
$options[''] = __( 'Select a value', 'woocommerce'); // default value
foreach ($dog_breeds as $key => $term)
$options[$term] = $term; // <=== <=== <=== Here the correct array
echo '<div class="options_group">';
woocommerce_wp_select( array(
'id' => '_select',
'label' => __( 'My Select Field', 'woocommerce' ),
'options' => $options, //this is where I am having trouble
'value' => $value,
) );
echo '</div>';
}
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){
// Select
$woocommerce_select = $_POST['_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );
else {
update_post_meta( $post_id, '_select', '' );
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。
在 WooCommerce 3+ 中测试并有效。你会得到类似的东西(用你的品种):
| 归档时间: |
|
| 查看次数: |
8713 次 |
| 最近记录: |