Reputation: 23
I don't know much about PHP yet, but I'm trying to place some content in my single product pages by using the woocommerce_before_add_to_cart_form
hook.
I succeeded in making a code that prints my text and the Total sales of my products. The code looks like this:
add_action( 'woocommerce_before_add_to_cart_form', 'production_time', 11 );
function production_time() {
global $product;
$production_time = $product->get_total_sales();
if ( $production_time ) echo '<p class="ri ri-clock">' . sprintf( __( ' Productietijd: %s', 'woocommerce' ), $production_time ) . '</p>';
}
But instead of product total sales I want my product custom field value to be displayed.
This is the custom field I added fullfilment_production_time
custom field:
I tried changing the get_total_sales()
to get_fullfilment_production_time()
but that didn't work.
I also tried this one:
add_action( 'woocommerce_before_add_to_cart_form', 'production_time', 11 );
function production_time() {
global $product;
$production_time = $product->get_post_meta( get_the_ID(), 'fullfilment_production_time', true );
if ( $production_time ) echo '<p class="ri ri-clock">' . sprintf( __( ' Productietijd: %s', 'woocommerce' ), $production_time ) . '</p>';
}
Any advice?
Upvotes: 2
Views: 5748
Reputation: 253784
There is a mistake in your code when using get_post_meta()
function in a wrong way. You can use different ways to get a product custom field value:
WC_Data
method get_meta()
this way:add_action( 'woocommerce_before_add_to_cart_form', 'production_time', 11 );
function production_time() {
global $product;
$production_time = $product->get_meta( 'fullfilment_production_time' );
if ( ! empty($production_time) ) {
echo '<p class="ri ri-clock">' . sprintf( __( ' Productietijd: %s', 'woocommerce' ), $production_time ) . '</p>';
}
}
get_post_meta()
function this way:add_action( 'woocommerce_before_add_to_cart_form', 'production_time', 11 );
function production_time() {
global $product;
$production_time = get_post_meta( $product->get_id(), 'fullfilment_production_time', true );
if ( ! empty($production_time) ) {
echo '<p class="ri ri-clock">' . sprintf( __( ' Productietijd: %s', 'woocommerce' ), $production_time ) . '</p>';
}
}
get_field()
function this way:add_action( 'woocommerce_before_add_to_cart_form', 'production_time', 11 );
function production_time() {
global $product;
$production_time = get_field( 'fullfilment_production_time', $product->get_id() );
if ( ! empty($production_time) ) {
echo '<p class="ri ri-clock">' . sprintf( __( ' Productietijd: %s', 'woocommerce' ), $production_time ) . '</p>';
}
}
Upvotes: 5