Archived topic
Changing image appearing for product if not purchased
7 replies · Started by William on October 25, 2021
Hi there,
I absolutely love GeneratePress and nearly have a website ready to go live, except for one bit. I have a piece of code that states if a product has been purchased or not:
function db_user_has_bought_product() {
if ( ! class_exists( 'WooCommerce' ) || ! is_user_logged_in() ) {
return;
}
$product = wc_get_product();
$id = $product->get_id();
if ( wc_customer_bought_product( '', get_current_user_id(), $id ) ) {
return true;
}
}
On one specific page only (where I show a selection of products), I would like to be able to change the product images to something else (i.e. an image with a lock sign, suggesting the product has not been bought yet).
Is there a way to change the product image on one page if the product has not been bought yet, such as the below image?

Hi William,
I think what you need is a lock overlay instead of an image replacement.
Try adding this PHP:
add_action('woocommerce_before_shop_loop_item_title',function(){
if( !db_user_has_bought_product() ){
echo '<div class="lock-overlay">
<div class="lock-wrapper">
<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="lock" class="svg-inline--fa fa-lock fa-w-14" role="img" viewBox="0 0 448 512"><path fill="currentColor" d="M400 224h-24v-72C376 68.2 307.8 0 224 0S72 68.2 72 152v72H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48zm-104 0H152v-72c0-39.7 32.3-72 72-72s72 32.3 72 72v72z"/></svg>
</div>
</div>';
}
});
And then add this CSS:
.lock-overlay{
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 10;
}
.lock-wrapper{
display: flex;
align-content: center;
justify-content: center;
align-items: center;
height: 100%;
background-color: rgba( 255, 255, 255, 0.8);
}
.lock-wrapper > svg {
width: 20px;
color: black;
}
That's absolutely amazing - thank you! That does the job perfectly for the shop page. However, I was hoping to have the functionality only appear on a standalone page which has hand selected products (and not on the shop page):

Is there a way to only show lock signs for products not bought when shown the products or a specific page only (using the hand picked gutenberg woocommerce block)?
Kind regards,
Willl
Hi there,
not easily doable when using a Woocommerce Block - if you try a Woocomemrce Shortcode instead you should find Elvins code will work.
Hi there,
That's absolutely perfect thank you! I stuck the CSS on the specific page and wonder if I can add your code to just that page too? Otherwise, the shop will show the padlock etc.?

In Elvins snippet - this line:
if( !db_user_has_bought_product() ){
try this:
if( is_page('the-page-slug') && !db_user_has_bought_product() ){
To check for the specific page you want it applied to
Perfect thank you! :)
Glad we could be of help!