Search code examples
csswordpresswoocommercewoocommerce-memberships

find user membership plan WooCommerce


I want to find the logged-in user's WooCommerce membership plan and then add CSS. Something like this code but this code doesn't work.

$user_id = get_current_user_id();
if ( wc_memberships_is_user_active_member( $user_id, '1-level' ) ) {
    echo '<style>option[value=3333] {display:none;} option[value=3334] {display:none;}</style>';
} else if ( wc_memberships_is_user_active_member( $user_id, '2-level' ) ) {
    echo '<style>option[value=3332] {display:none;} option[value=3334] {display:none;}</style>';
}
else if ( wc_memberships_is_user_active_member( $user_id, '3-level' ) ) {
    echo '<style>option[value=3332] {display:none;} option[value=3333] {display:none;}</style>';
}

Solution

  • You can do this through a wordpress hook which will echo the css in the correct place on the page. The best hook to use would be the wp_head action.

    You can wrap your code like so:

    add_action( 'wp_head', function() {
      $user_id = get_current_user_id();
    
      if ( wc_memberships_is_user_active_member( $user_id, '1-level' ) ) {
        echo '<style>option[value=3333] {display:none;} option[value=3334] {display:none;}</style>';
      } else if ( wc_memberships_is_user_active_member( $user_id, '2-level' ) ) {
        echo '<style>option[value=3332] {display:none;} option[value=3334] {display:none;}</style>';
      } else if ( wc_memberships_is_user_active_member( $user_id, '3-level' ) ) {
        echo '<style>option[value=3332] {display:none;} option[value=3333] {display:none;}</style>';
      }
    });
    

    You should also do a check inside that function to make sure you are on the correct page before outputting the css.