Wordpress Woocommerce自定义下拉问题

时间:2015-12-01 18:31:38

标签: php wordpress drop-down-menu woocommerce wpdb

我正在尝试在变量产品上添加动态下拉选择列表,但是foreach循环不起作用。出现选择框但它为空。打印阵列会显示正确的信息。我好像错过了一个状态问题。

所需功能:每个用户都有一个唯一的字符列表,他们需要能够在此变量产品页面上进行选择。 (单品有多种选择。)

此代码在主题模板页面上完美运行。 (childtheme)/testpage.php

它不适用于自定义woocommerce模板文件。地点:(childtheme)/woocommerce/variable/single-product/add-to-cart/variable.php

以下是代码:

<?php 
$clickedChar = $_GET['cc'];
$myChars = fyxt_myCharList ($fyxtAccountID); 
?>

<html>
<select name="char_list" required>
  <option value="">Select...</option>
</html>

<?php
    foreach($myChars as $clist){
        echo '<option value="'.$clist->idfyxt_character.'"'.(($clickedChar == $clist->idfyxt_character) ? ' selected="selected">' : '>' ).$clist->character_name.'</option>'; 
    }
?>
<html>
</select>
</html>

就像我说的这个代码在testpage.php主题模板页面上完美运行。但不是在woocommerce模板页面上。它并没有在foreach中循环。

我也遇到了调用Wordpress用户ID的问题,并被迫包含

$current_user = wp_get_current_user();

具体而言,模板页面通常不需要。我怀疑这里有类似的问题。或者至少是问题所在的线索。

感谢您的帮助和想法!

1 个答案:

答案 0 :(得分:1)

我已经猜到了fyxt_myCharList()函数的简化版本。使用woocommerce_before_add_to_cart_button挂钩,我们可以将一些代码添加到变量产品的页面,而无需修改添加到购物车模板。

还要注意在下拉菜单中使用的精彩小功能selected()

add_action( 'woocommerce_before_add_to_cart_button', 'so_34027544_custom_dropdown' );
function so_34027544_custom_dropdown(){
    global $product;
    if( is_product() && $product->is_type( 'variable' ) ){

        $clickedChar = isset( $_GET['cc'] ) && in_array( $_GET['cc'], fyxt_myCharList() ) ? $_GET['cc'] : '';
        $myChars = fyxt_myCharList(); 
        ?>

        <select name="char_list" required>
          <option value=""><?php _e( 'Select...', 'my-textdomain' );?></option>

            <?php
                foreach($myChars as $clist){
                    echo '<option value="'.$clist.'"'. selected( $clickedChar, $clist, false ) . '>' .$clist.'</option>'; 
                }
            ?>

        </select>

        <?php
    }
}


function fyxt_myCharList(){
    return array( 'a', 'b', 'c', 'd', 'e' );
}