woocommerce - 在添加动作时将产品传递给自定义功能

时间:2016-05-22 16:38:59

标签: php wordpress woocommerce

我正在尝试为woocommerce hook woocommerce_add_cart_item_data添加一个动作,在这里我试图在我用来挂钩的自定义函数中获取产品ID。为此,我在函数内部使用了get_the_ID(),但它不起作用。有没有办法在执行add_action时将woocommerce产品ID传递给我的自定义函数?

我的代码:

add_action('woocommerce_add_cart_item_data', 'order_session_date');

function order_session_date() {
   global $woocommerce;
   $product_id = get_the_ID();
   $sched_val = get_post_meta($product_id, '_sched_val', true);
   $data = array(
       $data_dates = $sched_val
   );
   WC()->session->set('name_for_your_data', $data);
}

1 个答案:

答案 0 :(得分:3)

它是一个过滤器,第二个参数是id,确保你返回第一个参数。

public enum Color {
    BLUE, BLACK, JOKER
}
public class Player {
    private int id;
    private ArrayList<Color> politicCards;
    public Player(int id){
        this.setId(id);
    }
    public ArrayList<Color> getPoliticCards() {
        return politicCards;
    }
    public void setPoliticCards(ArrayList<Color> politicCards) {
        this.politicCards = politicCards;
    }   

}
public class PlayerTest {
    @Test
    public void PoliticCardsTest(){
        Player player = new Player(1);
        player.getPoliticCards().add(Color.BLACK);
        player.getPoliticCards().add(Color.BLUE);
        player.getPoliticCards().add(Color.JOKER);
        assertEquals(Color.BLACK,player.getPoliticCards().get(0));
    }

}