Woocommerce cart custom field error on update - wordpress

I'm trying to add a custom field on each product on cart. I got the code from
WooCommerce: Add input field to every item in cart
but the update is not working. I tried to change the global $woocommerce to WC() but still it gives me 500 (Internal Server Error) on chrome console everytime I click update. heres the code:
cart.php:
<td class="product-url">
<?php
$html = sprintf( '<div class="url"><input type="text" name="cart[%s][url]" value="%s" size="4" title="Url" class="input-text url text" /></div>', $cart_item_key, esc_attr( $values['url'] ) );
echo $html;
?>
function.php (This is not a snippet so do not run):
// get from session your URL variable and add it to item
add_filter('woocommerce_get_cart_item_from_session', 'cart_item_from_session', 99, 3);
function cart_item_from_session( $data, $values, $key ) {
$data['url'] = isset( $values['url'] ) ? $values['url'] : '';
return $data;
}
// this one does the same as woocommerce_update_cart_action() in plugins\woocommerce\woocommerce-functions.php
// but with your URL variable
// this might not be the best way but it works
add_action( 'init', 'update_cart_action', 9);
function update_cart_action() {
global $woocommerce;
if ( ( ! empty( $_POST['update_cart'] ) || ! empty( $_POST['proceed'] ) ) && $woocommerce->verify_nonce('cart')) {
$cart_totals = isset( $_POST['cart'] ) ? $_POST['cart'] : '';
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
if ( isset( $cart_totals[ $cart_item_key ]['url'] ) ) {
$woocommerce->cart->cart_contents[ $cart_item_key ]['url'] = $cart_totals[ $cart_item_key ]['url'];
}
}
}
}
}
// this is in Order summary. It show Url variable under product name. Same place where Variations are shown.
add_filter( 'woocommerce_get_item_data', 'item_data', 10, 2 );
function item_data( $data, $cart_item ) {
if ( isset( $cart_item['url'] ) ) {
$data['url'] = array('name' => 'Url', 'value' => $cart_item['url']);
}
return $data;
}
// this adds Url as meta in Order for item
add_action ('woocommerce_add_order_item_meta', 'add_item_meta', 10, 2);
function add_item_meta( $item_id, $values ) {
woocommerce_add_order_item_meta( $item_id, 'Url', $values['url'] );
}

Related

Shortcode that display a single product attribute for a WooCommerce product

I am looking for a way to display a specific attribute on the single Product page of WooCommerce.
I found this code in the folling topic; Shortcode that display all product attributes set for a WooCommerce product
function get_product_attributes_shortcode($atts ) {
// Extract shortcode attributes
extract( shortcode_atts( array(
'id' => get_the_ID(),
), $atts, 'display-attributes' ) );
global $product;
if ( ! is_a($product, 'WC_Product') ) {
$product = wc_get_product( $id );
}
if ( is_a($product, 'WC_Product') ) {
$html = []; // Initializing
foreach ( $product->get_attributes() as $attribute => $values ) {
$attribute_name = wc_attribute_label($values->get_name());
$attribute_data = $values->get_data();
$is_taxonomy = $attribute_data['is_taxonomy'];
$option_values = array(); // Initializing
// For taxonomy product attribute values
if( $is_taxonomy ) {
$terms = $values->get_terms(); // Get attribute WP_Terms
// Loop through attribute WP_Term(s)
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $attribute );
$option_values[] = ''.$term->name.'';
}
}
// For "custom" product attributes values
else {
// Loop through attribute option values
foreach ( $values->get_options() as $term_name ) {
$option_values[] = $term_name;
}
}
$html[] = '<strong>' . $attribute_name . '</strong>: ' . implode(', ', $option_values);
}
return '<div class="product-attributes">' . implode(' | ', $html) . '<div>';
}
}
add_shortcode( 'display-attributes', 'get_product_attributes_shortcode' );
I can display all attributes by using the shortcode [display-attributes] but I want to display only one specific attribute (in my case the attribute is "Kunstenaar"). However I don't know how to adjust the code to make this work. Anyone who can help me out?
If you need just specific attribute, you don't have to get them all and then go through them. WC have function get_attribute() - documentation
function get_product_attributes_shortcode( $atts ) {
extract( shortcode_atts( array(
'id' => get_the_ID(),
), $atts, 'display-attributes' ) );
global $product;
if ( ! is_a($product, 'WC_Product') ) {
$product = wc_get_product( $id );
}
if ( is_a($product, 'WC_Product') ) {
$kunstenaar = $product->get_attribute( 'Kunstenaar' );
return '<div class="product-attributes"><strong>Kunstenaar</strong>: ' . $kunstenaar . '<div>';
}
}
add_shortcode( 'display-attributes', 'get_product_attributes_shortcode' );

Allow shortcodes in WooCommerce variation attributes in Cart, Checkout and Order pages

I have a product with a few variations that need to show a shortcode that returns a date in the format Month-YYYY: [prox_meses="1"].
After googling a bit I managed to allow shortcodes in the single product page, inside the variations dropdown using the following code:
// Single product page
function display_shortcode_in_variation_names( $term, $term_obj ) {
$product = wc_get_product();
$id = $product->get_id();
if ( empty( $term ) || empty( $id ) ) {
return $term;
}
if ( $product->is_type( 'variable' ) ) {
$product_variations = $product->get_available_variations();
} else {
return $term;
}
foreach ( $product_variations as $variation ) {
if ( count( $variation['attributes'] ) > 1 ) {
return $term;
}
$attribute = array_values( $variation['attributes'] )[0];
if ( $attribute === $term_obj->slug ) {
$term = do_shortcode($term);
}
}
return $term;
}
add_filter( 'woocommerce_variation_option_name', 'display_shortcode_in_variation_names', 10, 2 );
But the shortcode isn't working in the Cart, Checkout, or Order information. I'm not sure how to get that working.

How to display Advanced custom field data in new order email in woocommerce

I have advanced custom field plugin and i have added a custom field to my product the label name is (stock_number) my question is how do it display/show this field data in the new order email.
The below code should do the trick.
Option1:
add_action( 'woocommerce_order_item_meta_start', 'ts_order_item_meta_start', 10, 4 );
function ts_order_item_meta_start( $item_id, $item, $order, $plain_text ) {
if( $stock_number = get_field( 'stock_number', $item->get_product_id() ) ;
echo $stock_number;
}
Option2:
add_action( 'woocommerce_email_order_details', 'display_stock_email_order_details', 10, 4 );
function display_stock_email_order_details( $order, $sent_to_admin, $plain_text, $email ) {
foreach( $order->get_items() as $item ) {
if( $stock_number = get_field( "stock_number", $item->get_product_id() ) ){
echo '<p><strong>'.__('Stock Number').': </strong>'.$stock_number.'</p>';
}
}
}
Option3:
The below code will replace the Product Title with the ACF Custom Value.
add_filter( 'woocommerce_order_item_name', 'custom_order_item_name', 10, 2 );
function custom_order_item_name( $item_name, $item ) {
// Targeting email notifications only
if( is_wc_endpoint_url() )
return $item_name;
// Get the WC_Product object (from order item)
$product = $item->get_product();
if( $stock_number = get_field('stock_number', $product->get_id()) ) {
$item_name = '<p class="item-stck" style="margin:12px 0 0;">
<strong>' . __( 'Stock Number', 'woocommerce' ) . ': </strong>' . $stock_number . '</p>';
}
return $item_name;
}
Option4:
The below code will replace the Product Name with your custom field.
add_filter( 'woocommerce_order_item_name', 'custom_order_item_name', 10, 2 );
function custom_order_item_name( $item_name, $item ) {
// Get the WC_Product object (from order item)
$product = $item->get_product();
if( $stock_number = get_field('stock_number', $product->get_id()) ) {
$item_name = '<p class="item-stck" style="margin:12px 0 0;">
<strong>' . __( 'Stock Number', 'woocommerce' ) . ': </strong>' . $stock_number . '</p>';
}
return $item_name;
}

Change & Link of Add To Cart Button if product already in cart

I am trying to change the link & text of the Add to Cart button on the archive page if the products is already in cart.
I only allow quantity one per product to be added.
But the default way of Woocommerce is to direct to the single page with the notice.
Instead I would like the user to either
See the text "View Cart" and direct the user to the cart
or
See the text "Added" and have no link whatsoever.
Thank you
To change the text, you need the codes below.
add_filter('woocommerce_product_add_to_cart_text', 'wc_product_add_to_cart_text', 10, 2 );
add_filter('woocommerce_product_single_add_to_cart_text', 'wc_product_add_to_cart_text', 10, 2 );
function wc_product_add_to_cart_text( $text, $product ){
$product_cart_id = WC()->cart->generate_cart_id( $product->get_id() );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart ) {
$text = "View Cart";
}
return $text;
}
To redirect to cart, this will do it.
add_action( 'wp_loaded', 'wc_add_to_cart_action', 19 );
function wc_add_to_cart_action(){
if ( empty( $_REQUEST['add-to-cart'] ) || ! is_numeric( $_REQUEST['add-to-cart'] ) ) {
return;
}
$product_id = absint( $_REQUEST['add-to-cart'] );
$adding_to_cart = wc_get_product( $product_id );
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart && $adding_to_cart->is_sold_individually() ) {
wp_safe_redirect( wc_get_cart_url() );
exit;
}
}
or use this for the second part.
add_action( 'woocommerce_simple_add_to_cart', 'wc_simple_add_to_cart' );
function wc_simple_add_to_cart(){
global $product;
$product_cart_id = WC()->cart->generate_cart_id( $product->get_id() );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart ) {
remove_action( 'woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30 );
echo sprintf( '<form class="cart">%s</form>', wc_get_cart_url(), __( 'View Cart', 'woocommerce' ) );
}
}
update
for shop page you need this code:
add_filter('woocommerce_product_add_to_cart_url', 'wc_product_add_to_cart_url', 10, 2 );
function wc_product_add_to_cart_url( $url, $product ){
$product_cart_id = WC()->cart->generate_cart_id( $product->get_id() );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart && is_shop() ) {
$url = wc_get_cart_url();
}
return $url;
}

How to add custom filed and save it in wordpress?

Following code I tried out But it is not save value of custom Fileds.
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'product', 'side', 'high' );
}
In above I have add code it is display when posttype is product
function cd_meta_box_cb( $product)
{
$values = get_post_custom( $product->ID );
$text = isset( $values['my_meta_box_text'] ) ? esc_attr($values['my_meta_box_text'][0] ) : ”;
?>
<p>
<label for="my_meta_box_text">Text Label</label>
<input type="text" name="my_meta_box_text" id="my_meta_box_text" value="<?php echo $text; ?>" />
</p>
<?php
}
In above code it will added the metabox with textbox and if value in metabox then it is display
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $product_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
}
I want to save data in a wp_postmeta table. Above code i have tried out. I am beginner in wordpress.Can any give me suggestion ?
Use This code for creating custom fields for post.
class Rational_Meta_Box {
private $screens = array(
'post',
);
private $fields = array(
array(
'id' => 'custom-field-1',
'label' => 'custom field 1',
'type' => 'text',
),
array(
'id' => 'custom-field-2',
'label' => 'custom field 2',
'type' => 'text',
),
);
/**
* Class construct method. Adds actions to their respective WordPress hooks.
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'save_post', array( $this, 'save_post' ) );
}
/**
* Hooks into WordPress' add_meta_boxes function.
* Goes through screens (post types) and adds the meta box.
*/
public function add_meta_boxes() {
foreach ( $this->screens as $screen ) {
add_meta_box(
'my-custom-fields',
__( 'my custom fields', 'wordpress' ),
array( $this, 'add_meta_box_callback' ),
$screen,
'advanced',
'high'
);
}
}
/**
* Generates the HTML for the meta box
*
* #param object $post WordPress post object
*/
public function add_meta_box_callback( $post ) {
wp_nonce_field( 'my_custom_fields_data', 'my_custom_fields_nonce' );
echo 'its for custom fields for post typle';
$this->generate_fields( $post );
}
/**
* Generates the field's HTML for the meta box.
*/
public function generate_fields( $post ) {
$output = '';
foreach ( $this->fields as $field ) {
$label = '<label for="' . $field['id'] . '">' . $field['label'] . '</label>';
$db_value = get_post_meta( $post->ID, 'my_custom_fields_' . $field['id'], true );
switch ( $field['type'] ) {
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s">',
$field['type'] !== 'color' ? 'class="regular-text"' : '',
$field['id'],
$field['id'],
$field['type'],
$db_value
);
}
$output .= $this->row_format( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
/**
* Generates the HTML for table rows.
*/
public function row_format( $label, $input ) {
return sprintf(
'<tr><th scope="row">%s</th><td>%s</td></tr>',
$label,
$input
);
}
/**
* Hooks into WordPress' save_post function
*/
public function save_post( $post_id ) {
if ( ! isset( $_POST['my_custom_fields_nonce'] ) )
return $post_id;
$nonce = $_POST['my_custom_fields_nonce'];
if ( !wp_verify_nonce( $nonce, 'my_custom_fields_data' ) )
return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->fields as $field ) {
if ( isset( $_POST[ $field['id'] ] ) ) {
switch ( $field['type'] ) {
case 'email':
$_POST[ $field['id'] ] = sanitize_email( $_POST[ $field['id'] ] );
break;
case 'text':
$_POST[ $field['id'] ] = sanitize_text_field( $_POST[ $field['id'] ] );
break;
}
update_post_meta( $post_id, 'my_custom_fields_' . $field['id'], $_POST[ $field['id'] ] );
} else if ( $field['type'] === 'checkbox' ) {
update_post_meta( $post_id, 'my_custom_fields_' . $field['id'], '0' );
}
}
}
}
new Rational_Meta_Box;
So it will create custom fields in your post type and also saved it too.
follow this for the references https://developer.wordpress.org/plugins/metadata/creating-custom-meta-boxes/
Just replace your add_action( 'save_post', 'cd_meta_box_save' ); function and put below code.
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $product_id )
{
if( isset( $_POST[ 'my_meta_box_text' ] ) ) {
update_post_meta( $product_id,'my_meta_box_text', $_POST['my_meta_box_text'] );
}
}
Full code like ( it's working fine and also save custom field in postmeta table)
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'side', 'high' );
}
function cd_meta_box_cb( $product)
{
$values = get_post_custom( $product->ID );
$text = isset( $values['my_meta_box_text'] ) ? esc_attr($values['my_meta_box_text'][0] ) : '';
?>
<p>
<label for="my_meta_box_text">Text Label</label>
<input type="text" name="my_meta_box_text" id="my_meta_box_text" value="<?php echo $text; ?>" />
</p>
<?php
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $product_id )
{
if( isset( $_POST[ 'my_meta_box_text' ] ) ) {
update_post_meta( $product_id,'my_meta_box_text', $_POST['my_meta_box_text'] );
}
}
Take a look at Pods.
It is a very powerful plugin for customization.
http://pods.io/

Resources