Custom fields woocommerce - php

I am displaying some custom fields on the woocommerce single product page with this
add_action( 'woocommerce_single_product_summary','add_custom_field', 20 );
function add_custom_field() {
global $post;
echo get_post_meta( $post->ID, 'Brand', true );
echo get_post_meta( $post->ID, 'Content', true );
return true;
}
This dispays only the values of the custom fields, but I would like the names before so it would look like this:
Brand: ...
Content: ...
The custom fields don't aplly to every product though, so for the products where the custom fields are not set, nothing should be displayed.

Use this:
add_action( 'woocommerce_single_product_summary', 'add_custom_field', 20 );
function add_custom_field() {
global $post;
$brand = get_post_meta( $post->ID, 'Brand', true );
$content = get_post_meta( $post->ID, 'Content', true );
if (!empty($brand)) {
echo 'Brand: '. $brand;
}
if (!empty($content)) {
echo 'Content: '. $content;
}
}

Try below code
add_action( 'woocommerce_single_product_summary', 'add_custom_field', 20 );
function add_custom_field() {
global $post;
$brand = get_post_meta( $post->ID, 'Brand', true );
$content = get_post_meta( $post->ID, 'Content', true );
if (!empty($brand)) {
echo 'Brand: '. $brand .'<br>';
}
if (!empty($content)) {
echo 'Content: '. $content .'<br>';
}
}

Related

Woocommerce - display different product thumbnails on category page

I would like to display a different thumbnail for some of my products, if they appear in specific categories.
I have removed the current thumbnails from the specific category and I am using a custom field to pull the new thumbnail for the products I want to replace, which is working great. However, when I try to call the normal thumbnail for the remaining products it doesn't work - any ideas?
add_action( 'woocommerce_before_main_content', 'remove_test_category_thumbnails', 10 );
function remove_test_category_thumbnails() {
if (is_product_category('test-category')) {
remove_action('woocommerce_before_shop_loop_item_title' , 'woocommerce_template_loop_product_thumbnail' , 10);
}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'add_test_category_thumbnails', 10 );
function add_test_category_thumbnails() {
global $post;
$testCatThumb = get_post_meta( $post->ID, 'step_dad_mug', true);
if (is_product_category('test-category') && (isset($testCatThumb)) ) {
echo wp_get_attachment_image( $testCatThumb );
}
else
echo woocommerce_get_product_thumbnail();
}
}
You need to echo the woocommerce_get_product_thumbnail. check below code.
add_action( 'woocommerce_before_main_content', 'remove_test_category_thumbnails', 10 );
function remove_test_category_thumbnails() {
if (is_product_category('test-category')) {
remove_action('woocommerce_before_shop_loop_item_title' , 'woocommerce_template_loop_product_thumbnail' , 10);
}
}
add_action( 'woocommerce_before_shop_loop_item_title', 'add_test_category_thumbnails', 10 );
function add_test_category_thumbnails() {
global $post;
$testCatThumb = get_post_meta( $post->ID, 'step_dad_mug', true);
if( is_product_category( 'test-category' ) && ( isset( $testCatThumb ) ) ) {
echo wp_get_attachment_image( $testCatThumb );
}else{
echo woocommerce_get_product_thumbnail();
}
}
The following function expects a post id, is that what you are passing it?
wp_get_attachment_image();
as part of your if condition, you could check the value is of the correct value type:
is_numeric($testCatThumb);
I tend to create readable variables, rather than having horrible conditions you have to parse with your brain every time you read it:
function add_test_category_thumbnails() {
global $post;
$testCatThumb = get_post_meta( $post->ID, 'step_dad_mug', true);
$isPostId = !empty($testCatThumb) && is_numeric($testCatThumb);
$isValidAttachmentId = is_product_category('test-category') && $isPostId;
$image = $isValidAttachmentId ? wp_get_attachment_image($testCatThumb) : '';
// display custom image, or fallback to woocommerce thumbnail
echo !empty($image) ? $image : woocommerce_get_product_thumbnail();
}

Improve the code for print json data

function add_price_calculate_tour() {
global $post;
$product = wc_get_product( $post->ID );
if( $product->is_type( 'tour_booking' ) ):
$priceAdult = (float) get_post_meta( $product->get_id(), '_regular_price', true );
$priceChild = (float) get_post_meta( $product->get_id(), 't_children_price', true );
$tour = json_encode(["priceAdult" => $priceAdult,"priceChild" => $priceChild]);
wp_add_inline_script( 'twentyseventeen-global', 'var tour = '.$tour.'', 'before' );
endif;
}
I would like to simplify or improve this code, what it does basically is to create an array with a value, and then create a json and print it in the footer.
Any suggestions?

Get the '_order_total_base_currency' value from the Aelia Currency Switcher and display at custom field meta-box

I like to get the value from the Aelia Currency Switcher plugin which is the '_order_total_base_currency' and make a simple USD conversion then display it on my custom field metabox. How do I fetch that value so I can use it for calculation, and then display?
Here is my code:
// Adding the metabox (on the right side)
add_action( 'add_meta_boxes', 'cdmb_add_meta_box');
function cdmb_add_meta_box() {
add_meta_box(
'woocommerce-order-my-custom',
__('USD Currency display'),
'cdmb_display_meta_box',
'shop_order',
'side',
'core'
);
}
// The metabox content
function cdmb_display_meta_box() {
// Get
$total_usd = (get_post_meta( $post->ID, '_order_total_base_currency', true )) / 0.75;
$total_usd .= get_post_meta( $post->ID, '_order_total_base_currency', true );
echo '<p>' . $total_usd . '</p>';
}
// Save/Update the meta data
add_action( 'save_post', 'cdmb_save_meta_box_data' );
function cdmb_save_meta_box_data( $post_id ) {
// Only for shop order
if ( 'shop_order' != $_POST[ 'post_type' ] )
return $post_id;
// Checking that is not an autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
## SETTING AND UPDATING DATA ##
update_post_meta( $post_id, 'total-usd', sanitize_text_field( $_POST[ 'total-usd' ] ) );
}
?>
After spending time with it, I found the answer. I am now able to fetch the value for '_order_total_base_currency' from the Aelia Currency Switcher plugin.
It needs the global $post; before the variable $total_usd.
The code should be this:
function cdmb_display_meta_box() {
// Get
global $post;
$total_usd = get_post_meta( $post->ID, '_order_total_base_currency', true );
echo '<p>' . $total_usd . '</p>';

How to show some few attributes on woocommerce category page?

I want to show two of many attributes of my products on category pages namely heating capacity and cooling capacity as i am making an online store in woocommerce and i am working with my custom theme. it is not a variation or something it's just a normal attribute with text which i would like to show something like this as you can see the heating and cooling system listed on the category page itself i tried the code
if (!function_exists('shop_attributes_in_loop')) {
function shop_attributes_in_loop(){
global $product;
$attributes = $product->get_attributes();
if(!empty($attributes)){
$attribute_single = array_keys($attributes);
$myArray = array();
echo '<div class="product_attributes">';
foreach ($attribute_single as $attribute => $value) {
$myArray[] = ucfirst($value);
}
echo implode(', ', $myArray).'</div>';
}
}
}
add_action('woocommerce_after_shop_loop_item', 'shop_attributes_in_loop');
but it shows something wierd like
Placement-of-outdoor-unit, Installation, Pa_model-no-indoor, Pa_model-no-outdoor etc.. can anyone help me..
You can use this snippet for getting custom field value at archive / category page:
add_action( 'woocommerce_after_shop_loop_item', 'custom_display_post_meta', 9 );
function custom_display_post_meta() {
global $product;
$heating_capacity = get_post_meta( $product->id, 'heating_capacity', true );
$cooling_capacity = get_post_meta( $product->id, 'cooling_capacity', true );
echo $heating_capacity;
echo $cooling_capacity;
}
you can read this article as reference: https://www.skyverge.com/blog/add-information-to-woocommerce-shop-page/
I actually found out how its to be done :)
add_action( 'woocommerce_after_shop_loop_item', 'custom_display_post_meta', 9 );
function custom_display_post_meta() {
global $product;
$attr = array('pa_cooling-capacity-watts', 'pa_heating-capacity-watts');
foreach ( $attr as $attribute ) {
$values = wc_get_product_terms( $product->id, $attribute, array( 'fields' => 'names' ) );
echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values );
}
}

get the modified date of post meta box

i'm searching for a way to display the modified date of a custom field / meta box. until now, i only know how to echo
the_modified_date('l, j.n.Y');
but this one only works with the entire post.
i'am using a meta_box for additional pdf files uploading, code:
<?php class PDF_Metabox_id1 {
function __construct() {
add_action( 'post_mime_types', array( $this, 'pdf_mime_type_id1' ) );
add_action( 'add_meta_boxes', array( $this, 'admin_scripts_id1' ), 5 );
add_action( 'add_meta_boxes', array( $this, 'metabox_add_id1' ) );
add_action( 'save_post', array( $this, 'pdf_save_postdata_id1') );
add_action( 'wp_ajax_refresh_pdf', array( $this, 'refresh_pdf_id1' ) ); }
function pdf_mime_type_id1() {
$post_mime_types['application/pdf'] = array( __( 'PDFs' ), __( 'Manage PDFs' ), _n_noop( 'PDF <span class="count">(%s)</span>', 'PDFs <span class="count">(%s)</span>' ) );
return $post_mime_types;
}
function admin_scripts_id1() {
wp_register_script( 'pdf_metabox_js', get_stylesheet_directory_uri() . '/js/pdf_metabox.js' );
}
function metabox_add_id1() {
$post_types = array( 'myposttype','anotherposttype' );
$context = 'normal'; $priority = 'low';
foreach( $post_types as $post_type ) {
add_meta_box( 'pdf_metabox_id1', __( 'PDF Box 1', 'pdf_metabox_id1' ), array( $this, 'pdf_metabox_id1' ), $post_type, $context, $priority );
wp_enqueue_media();
wp_enqueue_script( 'pdf_metabox_js' );
}
}
function pdf_metabox_id1( $post ) {
$original_post = $post; echo $this->pdf_metabox_html_id1( $post->ID ); $post = $original_post;
}
function pdf_item_id1( $id ) {
if(!$id) return; $pdf_url = esc_url_raw(wp_get_attachment_url($id)); $pdf = $pdf_url; return $pdf;
}
function pdf_metabox_html_id1( $post_id ) {
$current_value = ''; $post_meta = get_post_custom($post_id);
if( isset($post_meta['pdf_id_id1'][0] ) ) $current_value = $post_meta['pdf_id_id1'][0];
$return = ''; wp_nonce_field( plugin_basename( __FILE__ ), 'pdf_noncename' );
$return .= '<p>';
$return .= '<a title="'.__( 'PDF', 'pdf_metabox_id1' ).'" class="button button-primary insert-pdf-button" id="insert_pdf_button_id1" href="#" style="float:left">'.__( 'Upload / editiere PDF', 'pdf_metabox_id1' ).'</a><span id="pdf_spinner_id1" class="spinner" style="float:left"></span></p>';
$return .= '<div style="clear:both"></div>';
$return .= '<input type="hidden" name="pdf_id_id1" id="pdf_id_id1" value="'.$current_value.'">';
$return .= '<div style="clear:both"></div>';
$return .= '<div id="pdf_wrapper_id1">';
$pdf = $this->pdf_item_id1( $current_value ); if( empty( $pdf ) ) {
$return .= '<p>Diesem Feld ist kein PDF hinterlegt.</p>'; } else {
$return .= '<br />URL des PDF:<br /> ';
$return .= $pdf; }
$return .= '</div>';
return $return;
}
function pdf_save_postdata_id1($post_id){
if ( isset($_POST['post_type']) && 'post' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_post', $post_id ) ) return; } if ( !isset( $_POST['pdf_noncename'] ) || ! wp_verify_nonce( $_POST['pdf_noncename'], plugin_basename( __FILE__ ) ) ) return;
if(isset($_POST['pdf_id_id1']) ): update_post_meta($post_id, 'pdf_id_id1', sanitize_text_field( $_POST['pdf_id_id1'] ) );
else: if (isset($post_id)) {
delete_post_meta($post_id, 'pdf_id_id1'); }
endif;
}
function refresh_pdf_id1() {
if(isset($_POST['id'])){
$item = $_POST['id'];
if($item != '' && $item !=0){
$pdf = $this->pdf_item_id1( $item );
$ret = array();
if( !empty( $pdf ) ) {$ret['success'] = true;
$ret['pdf'] = $pdf; } else {
$ret['success'] = false; } } else {
$ret['success'] = true; $ret['pdf'] = ''; } } else {
$ret['success'] = false; } echo json_encode( $ret ); die();
}
}
$PDF_Metabox_id1 = new PDF_Metabox_id1();
in my theme i'm using:
$post_meta_id1 = get_post_custom(get_the_ID());
$pdf_id_id1 = $post_meta_id1['pdf_id_id1'][0];
$pdf_url_id1 = wp_get_attachment_url($pdf_id_id1);
...and now i want to display the modified date of this field. any ideas?
As per the comment
how do i save the modified date of this custom field and how do i get it?
You may need to check every custom field in loop one by one if any of custom fields doesnot matched with the current post data then save a new custom field to post_meta. then retrieve in your template/page.
Just an idea:
<?php
function attributes_save_postdata( $post_id ) {
$postcustom = get_post_custom( $post_id );
$is_modified = false;
foreach ( $postcustom as $key => $val ) {
var_dump( $val );
// check your post custom values and
$getpostmeta = get_post_meta( $post_id, 'your_meta_key', true );
// if database value ($getpostmeta) not equal to current post value($_POST['your_meta_key'])
if ( $getpostmeta != $_POST['your_meta_key'] ) {
$is_modified = true;
// if found any custom field updated set $modified = true
}
}
// if found any custom field updated add or update new date and time
if ( $is_modified ) {
$date = date( 'Y-m-d h:i:s' ); // example : 2016-02-02 12:00:00 current date and time
update_post_meta( $post_id, '_modifieddate', $date );
}
}
add_action( 'save_post', 'attributes_save_postdata' );
Then in your theme. get modified date.
$post_id = get_the_ID();
$getpostmeta = get_post_meta( $post_id, 'your_meta_key', true );
I think that wordpress built-in function about this would help you out even for the custom fields.
<p>Last modified: <?php the_modified_time(); ?></p>

Categories