Change a link's url and text using a hook

I have a WordPress site and would like to the a button’s text and url depending on some conditions. I’m new to WordPress and php and am not sure if I should do this with a hook, as I try below, or with Javascript such as window.onload .... How should I do this?

I have the following button:

<div class="wp-block-button">
    <a class="start-button" href="[add_to_cart_url id='1045']" style="border-radius:14px">BUY NOW</a>
</div>

I added the code below to functions.php but am not sure how to make it apply that actual method on the button… How can I make this work?

add_filter('start-button', 'button_switch');

function button_switch($link){
    if ( ! is_user_logged_in() ) {
        $button_text="BUY NOW";
        $button_url="[add_to_cart_url id='1045']";
    
    // User logged in
    } else {
        $current_user = wp_get_current_user();
    
        // User already bought product
        if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, 1045 ) ) {
            $button_text="GO TO PRODUCT";
            $button_url="/product/1045/";
    
        // User not yet bought product
        } else {
            $button_text="BUY NOW";
            $button_url="[add_to_cart_url id='1045']";
        }
    }

    $link->url = $button_url;
    $link->text = $button_text;

    return $link;
}

9 thoughts on “Change a link's url and text using a hook”

Leave a Comment