John Davidson

php - How can I add a counter below every product item in wordpress?

0 comments
Message:


I wanted to add a counter below every product item in WordPress website.....to show


Item order (fetched from order placed) ----out of (fetched from stock no.)
In simple words, I wanna add a counter that shows Ordered item out of Stock Item below every product.


Screenshot: https://prnt.sc/1u7j9on


***I have added these codes in functions.php to add that button ***


//Show Total Sales on Product Page
add_action( 'woocommerce_single_product_summary', 'wp_product_sold_count', 11 );
function wp_product_sold_count() {
global $product;
$total_sold = get_post_meta( $product->id, 'total_sales', true );
if ( $total_sold ) echo '
' . sprintf( __( 'Total Sold: %s', 'woocommerce' ), $total_sold ) . '

';
}

//Show Total Sales on Product Loop Pages (Shop, Category, etc.)

add_action( 'woocommerce_after_shop_loop_item', 'shop_product_sold_count', 11 );
function shop_product_sold_count() {
global $product;
$total_sold = get_post_meta( $product->id, 'total_sales', true );
if ( $total_sold) echo '
' . sprintf( __( 'Total Sold: %s', 'woocommerce' ), $total_sold ) . '

';
}


///Stock number showing
add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_show_stock_shop', 10 );

function bbloomer_show_stock_shop() {
global $product;
echo wc_get_stock_html( $product );
}


My Answer:
To add a counter below every product item in WordPress, you can modify the code you have already added in the functions.php file. You can add a counter that shows the ordered item out of the stock item by fetching the order placed and stock number.

Here is an example code snippet that you can add to your functions.php file:

php
add_action( 'woocommerce_after_shop_loop_item', 'show_product_counter', 10 );

function show_product_counter() {
global $product;

// Get the total sales for the product
$total_sold = get_post_meta( $product->get_id(), 'total_sales', true );

// Get the stock quantity for the product
$stock_quantity = $product->get_stock_quantity();

// Calculate the counter
$counter = $total_sold . ' out of ' . $stock_quantity;

// Display the counter below the product item
echo '
' . $counter . '
';
}


This code will display a counter below every product item on the shop page, showing the number of items sold out of the total stock quantity for each product.

You can style the counter using CSS to make it look like the screenshot you provided. Just add the necessary CSS styles to your theme's stylesheet.

Please make sure to test this code on a staging site before implementing it on your live site to avoid any issues.

Rate this post

5 of 5 based on 1129 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us