Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save EricBusch/10792f3cd92b8c3f7dbd36c6cd4dc572 to your computer and use it in GitHub Desktop.
Save EricBusch/10792f3cd92b8c3f7dbd36c6cd4dc572 to your computer and use it in GitHub Desktop.
Add a product specific custom attribute. These are not attributes that will be filterable via the WooCommerce Layered Nav. These attributes are stored specifically for a product. [datafeedr]
<?php
/**
* Add the custom attribute label "Special Promotion" to a product.
*
* @param array $attributes An array attributes.
* @param array $post An array of post data including ID, post_title, post_status, etc...
* @param array $product An array of product data returned from the Datafeedr API.
* @param array $set A post array for this Product Set with an array key of postmeta containing all post meta data.
* @param string $action The action the Product Set is performing. Value are either "insert" or "update".
*
* @return array Updated $attributes array.
*/
add_filter( 'dfrpswc_product_attributes', 'mycode_set_promo_attribute_label', 20, 5 );
function mycode_set_promo_attribute_label( $attributes, $post, $product, $set, $action ) {
// The label for the product field.
$label = 'Special Promotion';
// The product field to import.
$field = 'promo';
$sanitized_label = sanitize_title( $label );
if ( ! isset( $product[ $field ] ) ) {
return $attributes;
}
if ( isset( $attributes[ $sanitized_label ] ) ) {
return $attributes;
}
if ( ! is_array( $attributes ) && empty( $attributes ) ) {
$attributes = [];
}
$attributes[ $sanitized_label ]['name'] = $label;
return $attributes;
}
/**
* Set value for "Special Promotion" attribute.
*
* @param array|string $value The current value of the $attribute for this $post.
* @param string $attribute The slug of the attribute. Examples: pa_color or pa_shoe-size
* @param array $post An array of post data including ID, post_title, post_status, etc...
* @param array $product An array of product data returned from the Datafeedr API.
* @param array $set A post array for this Product Set with an array key of postmeta containing all post meta data.
* @param string $action The action the Product Set is performing. Value are either "insert" or "update".
*
* @return array|string The updated attribute's value.
*/
add_filter( 'dfrpswc_filter_attribute_value', 'mycode_set_promo_attribute_value', 30, 6 );
function mycode_set_promo_attribute_value( $value, $attribute, $post, $product, $set, $action ) {
// The label for the product field.
$label = 'Special Promotion';
// The product field to import.
$field = 'promo';
if ( ! isset( $product[ $field ] ) ) {
return $value;
}
if ( $attribute == $label ) {
return $product[ $field ];
}
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment