Search code examples
phpwordpresswoocommerceaccountwoocommerce-subscriptions

Change woocommerce subscription "shop" link inside my account page


I'm a newbie in coding and currently using woocommerce subscription plugin and wanted to change the default "shop" if I don't have any subscription. I want it to link to a specific product instead of the shop.

I want to change the red part: I want to change the red part

Below are the current code for this section:

<?php
        // translators: placeholders are opening and closing link tags to take to the shop page
        printf( esc_html__( 'Anda masih belum melanggan. Mula melanggan %sdi sini%s.', 'woocommerce-subscriptions' ), '<a href="' . esc_url( apply_filters( 'woocommerce_subscriptions_message_store_url', get_permalink( wc_get_page_id( 'shop' ) ) ) ) . '">', '</a>' );
        ?>
    </p>

<?php endif; ?>

I want to change the example.com/shop into something like example.com/product-category/myproduct

Any help will be appreciated.


Solution

  • To achieve that, you will need:

    • A conditional function that detect if the current user has an active subscription
    • A custom function hooked in woocommerce_subscriptions_message_store_url filter hook, where you will define your new URL linked to your product.

    Here is the code:

    // Conditional function detecting if the current user has an active subscription
    function has_active_subscription( $user_id=null ) {
        // if the user_id is not set in function argument we get the current user ID
        if( null == $user_id )
            $user_id = get_current_user_id();
    
        // Get all active subscrptions for a user ID
        $active_subscriptions = get_posts( array(
            'numberposts' => -1,
            'meta_key'    => '_customer_user',
            'meta_value'  => $user_id,
            'post_type'   => 'shop_subscription', // Subscription post type
            'post_status' => 'wc-active', // Active subscription
        ) );
        // if user has an active subscription
        if( ! empty( $active_subscriptions ) ) return true;
        else return false;
    }
    
    
    // Change woocommerce subscription “shop” link inside my account page
    add_filter( 'woocommerce_subscriptions_message_store_url', 'custom_subscriptions_message_store_url', 10, 1 );
    function custom_subscriptions_message_store_url( $url ){
    
        // If current user has NO active subscriptions 
        if( ! has_active_subscription() ){
    
            // HERE Define below the new URL linked to your product.
            $url = home_url( "/product-category/myproduct/" );
        }
        return $url;
    }
    

    This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    Tested and works