0

I'm trying to add a custom field just below the price in my Woocommerce theme. I was able to add simple html by using:

add_action( 'woocommerce_before_add_to_cart_form', 'SomeName' );

function SomeName() {

echo '<p>Some Text Here</p>';

}

But what I want to do is add a custom field key instead. I'm using this code for placing custom fields:

<?php 

$naslov = get_post_meta($post->ID, 'Naslov', true);

if ($naslov) { ?>

<h2 class="single-naslov-kat"><? echo $naslov; ?></h2>

<?php 

} else { 
// do nothing; 
}

?>

The code works great when I add it to content-single-product.php theme file. But I can't add it below the price through that file. And I have no idea how to incorporate it through functions.php.

If you have any other suggestions on how I might be able to add custom text below the price for each specific product that's ok too.

Any help would be greatly appreciated.

1 Answer 1

0

In your themes functions.php add the code,

//create custom field
function cfwc_create_custom_field() {
  $args = array(
    'id' => 'custom_field',
    'label' => __( 'Custom Field', 'cfwc' ),
    'class' => 'cfwc-custom-field',
    'desc_tip' => true,
    'description' => __( 'Enter Custom Field Description.', 'ctwc' ),
  );
  woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'cfwc_create_custom_field' );

// save custom field
function cfwc_save_custom_field( $post_id ) {
  $link = wc_get_product( $post_id );
  $title = isset( $_POST['custom_field'] ) ? $_POST['custom_field'] : '';
  $link->update_meta_data( 'custom_field', sanitize_text_field( $title ) );
  $link->save();
}
add_action( 'woocommerce_process_product_meta', 'cfwc_save_custom_field' );



// display custom field in single.php page
add_action('woocommerce_before_add_to_cart_form','cmk_additional_button');
function cmk_additional_button() {
  global $product;
  $custom_field = $product->get_meta('custom_field');
  if(!empty($custom_field)) {
    echo "<a href='$custom_field' target='_blank'><button type='button' class='button alt'>Custom Field</button></a>";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.