Save multiple datas in order WooCommerce - woocommerce

I have two customs fields in my product (image and texte), I all ready show it in the cart but when the order is complete, i can't find how can I show both in the admin order (I can show one of two ^^)
Here is the code :
// Add custom fields data as the cart item custom data
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_fields_data_as_custom_cart_item_data', 10, 2 );
function add_custom_fields_data_as_custom_cart_item_data($cart_item, $product_id){
if( isset($_FILES['image']) && !empty($_FILES['image']) && !empty($_POST['nom_pp']) ) {
$upload = wp_upload_bits( $_FILES['image']['name'], null, file_get_contents( $_FILES['image']['tmp_name'] ) );
$filetype = wp_check_filetype( basename( $upload['file'] ), null );
$upload_dir = wp_upload_dir();
$upl_base_url = is_ssl() ? str_replace('http://', 'https://', $upload_dir['baseurl']) : $upload_dir['baseurl'];
$base_name = basename( $upload['file'] );
$cart_item['file_upload'] = array(
'guid' => $upl_base_url .'/'. _wp_relative_upload_path( $upload['file'] ), // Url
'file_type' => $filetype['type'], // File type
'file_name' => $base_name, // File name
'title' => ucfirst( preg_replace('/\.[^.]+$/', '', $base_name ) ), // Title
);
$cart_item['nom_pp'] = $_POST['nom_pp'];
$cart_item['unique_key'] = md5( microtime().rand() ); // Avoid merging items
}
return $cart_item;
}
// Display custom cart item data in cart (optional)
add_filter('woocommerce_get_item_data', 'njengah_custom_item_data', 10, 2);
function njengah_custom_item_data($cart_item_data, $cart_item) {
if ( isset($cart_item['file_upload']['title']) ){
$cart_item_data[] = array(
'name' => __( 'Mon image ', 'woocommerce' ),
'value' => str_pad($cart_item['file_upload']['title'], 16, 'X', STR_PAD_LEFT) . '…',
);
}
if ( isset($cart_item['nom_pp']) ){
$cart_item_data[] = array(
'name' => __( 'Nom du papier peint ', 'woocommerce' ),
'value' => $cart_item['nom_pp'],
);
}
return $cart_item_data;
}
// Save Image data as order item meta data
add_action( 'woocommerce_checkout_create_order_line_item', 'njengah_field_update_order_item_meta', 20, 4 );
function njengah_field_update_order_item_meta( $item, $cart_item_key, $values, $order ) {
if ( isset($values['file_upload']) && isset($values['nom_pp']) ){
$item->update_meta_data($item, '_img_file', $values['file_upload']);
$item->update_meta_data($item, '_nom_pp', $values['nom_pp']);
}
}
// Admin orders: Display a linked button + the link of the image file
add_action( 'woocommerce_after_order_itemmeta', 'njengah_image_link_after_order_itemmeta', 10, 3 );
function njengah_image_link_after_order_itemmeta( $item_id, $item, $product ) {
// Only in backend for order line items (avoiding errors)
if( is_admin() && $item->is_type('line_item') && $file_data = $item->get_meta('_img_file') && $file_data = $item->get_meta('_nom_pp') ){
echo '<p>'.__("Voir l'image") . '</p>'; // Optional
echo '<p><code>'.$file_data['guid'].'</code></p>'; // Optional
echo '<p>'.$file_data['nom_pp'].'</p>'; // Optional
}
}
I think I need to edit the order meta data, but I don't know how can I do it :)

Related

Wordpress add meta key to Cart item

as I am trying to add one extra data so that I can fetch and filter the data according to the meta after successfull payment. Let me explain using code.
$cart_data = array(
'product_id' => $product_id,
'payment_type' => 'subscription',
'**what_is_being_promoted**' => $promoting,
);
WC()->cart->add_to_cart($product_id, 1, null, null, $cart_item_data);
now i would like to read the key 'what_is_being_promoted' in classifier_update_user_data_upon_payment hook.
how to achieve that.
You can use below filters/action to add additional data to cart item:
//Add custom cart item data
function zwtadd_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
if( isset( $_POST['what_is_being_promoted'] ) ) {
$cart_item_data['zwt_field'] = sanitize_text_field( $_POST['what_is_being_promoted'] );
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'zwtadd_cart_item_data', 10, 3 );
//Display custom item data in the cart
function zwt_get_item_data( $item_data, $cart_item_data ) {
if( isset( $cart_item_data['zwt_field'] ) ) {
$item_data[] = array(
'key' => __( 'Is promoted', 'text-domain' ),
'value' => wc_clean( $cart_item_data['zwt_field'] )
);
}
return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'zwt_get_item_data', 10, 2 );
//Add custom meta to order
function zwt_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
if( isset( $values['zwt_field'] ) ) {
$item->add_meta_data(__( 'Is promoted', 'text-domain' ), $values['zwt_field'], true);
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'zwt_checkout_create_order_line_item', 10, 4 );
Above code will add data to cart item, display data to cart and same will display in the order.

Add custom select field with validation to WooCommerce checkout page if certain products are in cart

I wish to add a custom select field with validation to the WooCommerce checkout page if certain products are in cart.
With my current code I retrieve the value of my custom WooCommerce form field. However, it display "array" at the order page.
I have an select field which have an option of 1 and 0. Upon selection of the select field, i want it to display either 1 or 0 at the order page but im unable to do so.
Please guide me on what should i do with my current codes:
//AMBASSADOR CUSTOM CHECKOUT FIELDS, CONTENT add marketplace for sameday TEST
add_action( 'woocommerce_after_checkout_billing_form', 'aym_custom_checkout_field' );
function aym_custom_checkout_field( $checkout ) {
//Check if Product in Cart
$prod_in_cart_17563 = aym_is_conditional_product_in_cart_17563( 212 );
if ( $prod_in_cart_17563 === true ) {
$domain = 'wocommerce';
$default = 'Y';
woocommerce_form_field( '_my_field_name', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => __( 'Market Place - Please Select Y to complete this order' ),
'required' => true,
'options' => array(
'Y' => __('1'),
'N' => __('0')
),'default' => $default),
$checkout->get_value( '_my_field_name' ) );
}
}
//AMBSSADOR BUNDLE add marketplace for same day pa rt 2
function aym_is_conditional_product_in_cart_17563( $product_id ) {
//Check to see if user has product in cart
global $woocommerce;
//flag no product in cart
$prod_in_cart_17563 = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id === $product_id ) {
//product is in cart!
$prod_in_cart_17563 = true;
}
}
return $prod_in_cart_17563;
}
//process orders in order page
// Custom checkout fields validation
add_action( 'woocommerce_checkout_process', 'custom_checkout_field_process' );
function custom_checkout_field_process() {
if ( isset($_POST['_my_field_name']) && empty($_POST['_my_field_name']) )
wc_add_notice( __( 'Please fill in "My 1st new field".' ), 'error' );
}
// Save custom checkout fields the data to the order
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_field_update_meta', 10, 2 );
function custom_checkout_field_update_meta( $order, $data ){
if( isset($_POST['_my_field_name']) && ! empty($_POST['_my_field_name']) )
$order->update_meta_data( '_my_field_name', sanitize_text_field( $_POST['_my_field_name'] ) );
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['_my_field_name']) update_post_meta( $order_id, 'My Field', esc_attr($_POST['_my_field_name']));
}
// View fields in Edit Order Page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_custom_fields_value_admin_order', 10, 1 );
function display_custom_fields_value_admin_order( $order ){
// Display the delivery option
if( $delivery_option = $order->get_meta('_my_field_name') )
echo '<p><strong>'.__('Delivery type').':</strong> ' . $delivery_option . '</p>';
}
// Display field value on the order edit page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta( $order ) {
if( $selectoption = $order->get_meta('_my_field_name') ) {
//$value = wc_get_hearaboutus_options()[$selectoptions];
$meta= get_post_meta( $post->ID, $selectoption, true );
$myvalues = unserialize( $meta );
echo '<p><strong>'.__('Market_Place').':</strong> ' . $myvalues . '</p>';
}
}
I have partly rewritten / modified your code with some (extra) features
The ability to check for multiple product IDs in the shopping cart
The custom field is only added if a certain product id is in the shopping cart
The possibility to check out if the custom field is not present (product ID is NOT in cart)
No possibility to checkout as long as the value 'Y' is not selected from the custom select menu (Product ID is IN cart)
Explanation via comment tags added in the code
// Add custom 'select' field after checkout billing form (if product ID is in cart)
function action_woocommerce_after_checkout_billing_form( $checkout ) {
// Check if Product in Cart
// Multiple product IDs can be entered, separated by a comma
$product_in_cart = is_product_in_cart( array( 212, 30, 815 ) );
// True
if ( $product_in_cart ) {
$domain = 'woocommerce';
$default = 'Y';
woocommerce_form_field( '_my_field_name', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => __( 'Market Place - Please Select Y to complete this order', $domain ),
'required' => true,
'options' => array(
'Y' => __( 'Y', $domain ),
'N' => __( 'N', $domain ),
),
'default' => $default,
), $checkout->get_value( '_my_field_name' ) );
}
}
add_action( 'woocommerce_after_checkout_billing_form', 'action_woocommerce_after_checkout_billing_form', 10, 1 );
// Function to check if a certain product ID is in cart
function is_product_in_cart( $targeted_ids ) {
// Flag no product in cart
$flag = false;
// WC Cart NOT null
if ( ! is_null( WC()->cart ) ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Check cart item for defined product Ids
if ( in_array( $cart_item['product_id'], $targeted_ids ) ) {
// Product is in cart
$flag = true;
// Break loop
break;
}
}
}
return $flag;
}
// Custom checkout 'select' field validation
function action_woocommerce_checkout_process() {
// Isset
if ( isset( $_POST['_my_field_name'] ) ) {
$domain = 'woocommerce';
$my_field_name = $_POST['_my_field_name'];
// Empty
if ( empty ( $my_field_name ) ) {
wc_add_notice( __( 'Please Select Y to complete this order', $domain ), 'error' );
}
// NOT empty but value is 'N'
if ( ! empty ( $my_field_name ) && $my_field_name == 'N' ) {
wc_add_notice( __( 'Please Select Y to complete this order', $domain ), 'error' );
}
}
}
add_action( 'woocommerce_checkout_process', 'action_woocommerce_checkout_process', 10, 0 );
// Save custom checkout 'select' field
function action_woocommerce_checkout_create_order( $order, $data ) {
// Isset
if ( isset( $_POST['_my_field_name'] ) ) {
$my_field_name = $_POST['_my_field_name'];
// NOT empty & equal to 'Y'
if ( ! empty( $my_field_name ) && $my_field_name == 'Y' ) {
$order->update_meta_data( '_my_field_name', sanitize_text_field( $my_field_name ) );
}
}
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );
// Display the custom 'select' field value on admin order pages after billing adress
function action_woocommerce_admin_order_data_after_billing_address( $order ) {
$domain = 'woocommerce';
// Get meta
$my_field_name = $order->get_meta( '_my_field_name' );
// NOT empty
if ( ! empty ( $my_field_name ) ) {
echo '<p><strong>' . __( 'Delivery type', $domain ) . ':</strong> ' . $order->get_meta( '_my_field_name' ) . '</p>';
}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'action_woocommerce_admin_order_data_after_billing_address', 10, 1 );
// Display the custom 'select' field value on 'order received' and 'order view' pages (frontend)
function action_woocommerce_order_details_after_order_table( $order ) {
$domain = 'woocommerce';
// Get meta
$my_field_name = $order->get_meta( '_my_field_name' );
// NOT empty
if ( ! empty ( $my_field_name ) ) {
echo '<p><strong>' . __( 'Delivery type', $domain ) . ':</strong> ' . $order->get_meta( '_my_field_name' ) . '</p>';
}
}
add_action( 'woocommerce_order_details_after_order_table', 'action_woocommerce_order_details_after_order_table', 10, 1 );

Add custom field as item meta data on the Order

I have added a custom field to the woocommerce products, it is working well with the following code. But my problem is how to add it to the cart_item_data
// Display Text in Admin Panel
add_action('woocommerce_product_options_general_product_data', 'product_custom_text_field');
function product_custom_text_field()
{
// Custom Product Text Field ( para Tex Area -> woocommerce_wp_textarea_input )
woocommerce_wp_text_input(
array(
'id' => '_optional_text_field',
'label' => __('Customize title', 'woocommerce'),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __('Customizable title for the field that the user must fill out.', 'woocommerce')
)
);
}
Save Fields
add_action('woocommerce_process_product_meta', 'product_custom_text_field_save');
function product_custom_text_field_save($post_id)
{
if (!empty($_POST['_optional_text_field'])) {
update_post_meta($post_id, '_optional_text_field', esc_attr($_POST['_optional_text_field']));
}
}
Display The Text in Product Page
add_action('woocommerce_single_variation', 'display_text_field');
function display_text_field()
{
global $post;
if (get_post_meta($post->ID, '_optional_text_field', true)) {
echo "<div class='titulo-c'><label>";
echo get_post_meta($post->ID, '_optional_text_field', true);
echo "</label></div>";
return;
}
echo __('FREE LOCAL SHIPPING', 'woocommerce');
}
So far it works without problems, now I want to add it to the cart_item_data, with the following code, but it does not work for me.
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 25, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {
$custom_data = array() ;
$custom_data[ "_optional_text_field"] = isset( $_POST['_optional_text_field'] ) ? sanitize_text_field ( $_POST['_optional_text_field'] ) : "" ;
$cart_item_meta ['custom_data'] = $custom_data ;
return $cart_item_meta;
}
Display custom data on cart and checkout page.
add_filter( 'woocommerce_get_item_data', 'get_item_data' , 25, 2 );
function get_item_data ( $other_data, $cart_item ) {
if ( isset( $cart_item [ 'custom_data' ] ) ) {
$custom_data = $cart_item [ 'custom_data' ];
$other_data[] = array( 'name' => 'Title',
'display' => $custom_data['_optional_text_field'] );
}
return $other_data;
}
As a result, it only appears to me: Title: ________
I will appreciate any suggestions to make my code work.
Make the following changes to your code as below, this should work.
/**
* Add data to cart item
*/
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 25, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {
global $woocommerce;
$mytitle_form_data = get_post_meta($product_id, '_optional_text_field', true);
$custom_data = array() ;
$custom_data[ "_optional_text_field"] = $mytitle_form_data;
$cart_item_meta ['custom_data'] = $custom_data ;
return $cart_item_meta;
}

Adding New Stock Status to Products in Woocommerce [duplicate]

I am using the following code to add new stock statuses in WooCommerce 4+
The new statuses are:
Preorder
Contact us
function add_custom_stock_type() {
?>
<script type="text/javascript">
jQuery(function(){
jQuery('._stock_status_field').not('.custom-stock-status').remove();
});
</script>
<?php
woocommerce_wp_select( array( 'id' => '_stock_status', 'wrapper_class' => 'custom-stock-status', 'label' => __( 'Stock status', 'woocommerce' ), 'options' => array(
'instock' => __( 'Available', 'woocommerce' ), //changed the name
'outofstock' => __( 'Sold out', 'woocommerce' ), //changed the name
'onbackorder' => __( 'Preorder : Pending Distributor release', 'woocommerce' ), //changed the name
'contact' => __( 'Contact us for Availability', 'woocommerce' ), //added new one
'preorder' => __( 'On Preorder: Pending Distributor release', 'woocommerce' ), //added new one
), 'desc_tip' => true, 'description' => __( 'Controls whether or not the product is listed as "in stock" or "out of stock" on the frontend.', 'woocommerce' ) ) );
}
add_action('woocommerce_product_options_stock_status', 'add_custom_stock_type');
function save_custom_stock_status( $product_id ) {
update_post_meta( $product_id, '_stock_status', wc_clean( $_POST['_stock_status'] ) );
}
add_action('woocommerce_process_product_meta', 'save_custom_stock_status',99,1);
function woo_add_custom_general_fields_save_two( $post_id ){
// Select
$woocommerce_select = $_POST['_stock_status'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_stock_status', esc_attr( $woocommerce_select ) );
else
update_post_meta( $post_id, '_stock_status', '' );
}
function woocommerce_get_custom_availability( $data, $product ) {
switch( $product->stock_status ) {
case 'instock':
$data = array( 'availability' => __( 'Available', 'woocommerce' ), 'class' => 'in-stock' ); //changed name
break;
case 'outofstock':
$data = array( 'availability' => __( 'Sold Out', 'woocommerce' ), 'class' => 'out-of-stock' ); //changed name
break;
case 'onbackorder':
$data = array( 'availability' => __( 'Preorder : Pending Distributor release', 'woocommerce' ), 'class' => 'onbackorder' ); //changed name
break;
case 'contact':
$data = array( 'availability' => __( 'Contact us for Availability', 'woocommerce' ), 'class' => 'contact' ); //added new one
break;
case 'preorder':
$data = array( 'availability' => __( 'On Preorder : Pending Distributor release', 'woocommerce' ), 'class' => 'preorder' ); //added new one
break;
}
return $data;
}
add_action('woocommerce_get_availability', 'woocommerce_get_custom_availability', 10, 4);
Works:
Backend: The new status is added in the dropdown menu, I can select the status I want
Does not work:
Front end: on single product page is not showing the correct status
Backend: Display the new status on the admin products list table
Someone who can assist me with this?
Last update: 04/22 - Tested in WordPress 5.9.2 & WooCommerce 6.3.1
Code goes in functions.php file of the active child theme (or active theme).
Use woocommerce_product_stock_status_options
instead of woocommerce_product_options_stock_status.
This way you can immediately add a status instead of replace the existing dropdown
Also use woocommerce_get_availability_text & woocommerce_get_availability_class
opposite woocommerce_get_availability.
This way you don't have to add the existing statuses again
// Add new stock status options
function filter_woocommerce_product_stock_status_options( $status ) {
// Add new statuses
$status['pre_order'] = __( 'Pre order', 'woocommerce' );
$status['contact_us'] = __( 'Contact us', 'woocommerce' );
return $status;
}
add_filter( 'woocommerce_product_stock_status_options', 'filter_woocommerce_product_stock_status_options', 10, 1 );
// Availability text
function filter_woocommerce_get_availability_text( $availability, $product ) {
// Get stock status
switch( $product->get_stock_status() ) {
case 'pre_order':
$availability = __( 'Pre order', 'woocommerce' );
break;
case 'contact_us':
$availability = __( 'Contact us', 'woocommerce' );
break;
}
return $availability;
}
add_filter( 'woocommerce_get_availability_text', 'filter_woocommerce_get_availability_text', 10, 2 );
// Availability CSS class
function filter_woocommerce_get_availability_class( $class, $product ) {
// Get stock status
switch( $product->get_stock_status() ) {
case 'pre_order':
$class = 'pre-order';
break;
case 'contact_us':
$class = 'contact-us';
break;
}
return $class;
}
add_filter( 'woocommerce_get_availability_class', 'filter_woocommerce_get_availability_class', 10, 2 );
Use woocommerce_admin_stock_html to display the new stock status on the admin products list table
// Admin stock html
function filter_woocommerce_admin_stock_html( $stock_html, $product ) {
// Simple
if ( $product->is_type( 'simple' ) ) {
// Get stock status
$product_stock_status = $product->get_stock_status();
// Variable
} elseif ( $product->is_type( 'variable' ) ) {
foreach( $product->get_visible_children() as $variation_id ) {
// Get product
$variation = wc_get_product( $variation_id );
// Get stock status
$product_stock_status = $variation->get_stock_status();
/*
Currently the status of the last variant in the loop will be displayed.
So from here you need to add your own logic, depending on what you expect from your custom stock status.
By default, for the existing statuses. The status displayed on the admin products list table for variable products is determined as:
- Product should be in stock if a child is in stock.
- Product should be out of stock if all children are out of stock.
- Product should be on backorder if all children are on backorder.
- Product should be on backorder if at least one child is on backorder and the rest are out of stock.
*/
}
}
// Stock status
switch( $product_stock_status ) {
case 'pre_order':
$stock_html = '<mark class="pre-order" style="background:transparent none;color:#33ccff;font-weight:700;line-height:1;">' . __( 'Pre order', 'woocommerce' ) . '</mark>';
break;
case 'contact_us':
$stock_html = '<mark class="contact-us" style="background:transparent none;color:#cc33ff;font-weight:700;line-height:1;">' . __( 'Contact us', 'woocommerce' ) . '</mark>';
break;
}
return $stock_html;
}
add_filter( 'woocommerce_admin_stock_html', 'filter_woocommerce_admin_stock_html', 10, 2 );
Optional: if desired, the custom stock status can be used in hooks where you already have access to the $product object or you can use global $product.
1) No access to the $product object, use global $product as is the case for example with the woocommerce_shop_loop_item_title or the woocommerce_single_product_summary hook
function woocommerce_my_callback() {
// An example based on global $product
// Get the global product object
global $product;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get stock status
$product_stock_status = $product->get_stock_status();
// Use this line during testing, delete afterwards!
echo '<p style="color:red;font-size:20px;">DEBUG INFORMATION = ' . $product_stock_status . '</p>';
// Compare
if ( $product_stock_status == 'My custom stock status' ) {
// Etc..
}
}
}
add_action( 'woocommerce_shop_loop_item_title', 'woocommerce_my_callback', 10 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_my_callback', 10 );
2) Access to the $product object, because it's passed by default to the callback function. As is the case for example with the woocommerce_get_price_html hook
function filter_woocommerce_get_price_html( $price, $product ) {
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get stock status
$product_stock_status = $product->get_stock_status();
// Use this line during testing, delete afterwards!
echo '<p style="color:red;font-size:20px;">DEBUG INFORMATION = ' . $product_stock_status . '</p>';
// Compare
if ( $product_stock_status == 'My custom stock status' ) {
// Etc..
// $price .= ' my text';
}
}
return $price;
}
add_filter( 'woocommerce_get_price_html', 'filter_woocommerce_get_price_html', 10, 2 );
In addition to filters provided by 7uc1f3r woocommerce_product_export_product_column_stock_status filter is required to display custom stock status in exported products CSV file:
function add_custom_stock_csv_data( $_, $product ) {
$status = $product->get_stock_status( 'edit' );
switch( $status ) {
case 'pre_order':
case 'contact_us':
return $status;
case 'onbackorder':
return 'backorder';
case 'instock':
return 1;
default:
return 0;
}
}
add_filter( 'woocommerce_product_export_product_column_stock_status', 'add_custom_stock_csv_data', 10, 2 );

Create custom notification in post insert in buddypress

I want to add custom notification in the time of post creation. I have followed this url https://webdevstudios.com/2015/10/06/buddypress-adding-custom-notifications/
What i have done, I am adding custom notification in creation of project or bid post type. But it not working. Please check my code and let me what i have done wrong.
// this is to add a fake component to BuddyPress. A registered component is needed to add notifications
function custom_filter_notifications_get_registered_components( $component_names = array() ) {
// Force $component_names to be an array
if ( ! is_array( $component_names ) ) {
$component_names = array();
}
// Add 'custom' component to registered components array
array_push( $component_names, 'projectadd' );
// Return component's with 'custom' appended
return $component_names;
}
add_filter( 'bp_notifications_get_registered_components', 'custom_filter_notifications_get_registered_components' );
// this hooks to post creation and saves the post id
function bp_custom_add_notification( $post_id, $post ) {
if ( $post->post_type == 'project' || $post->post_type == 'bid' ) {
$post = get_post( $post_id );
$author_id = $post->post_author;
bp_notifications_add_notification( array(
'user_id' => $author_id,
'item_id' => $post_id,
'component_name' => 'projectadd',
'component_action' => 'projectadd_action',
'date_notified' => bp_core_current_time(),
'is_new' => 1,
) );
}
}
add_action( 'wp_insert_post', 'bp_custom_add_notification', 99, 2 );
// this gets the saved item id, compiles some data and then displays the notification
function custom_format_buddypress_notifications( $content, $item_id, $secondary_item_id, $total_items, $format = 'string', $action, $component ) {
// New custom notifications
if ( 'projectadd_action' === $action ) {
$post = get_post( $item_id );
$custom_title = $post->post_author . ' add the project ' . get_the_title( $item_id );
$custom_link = get_permalink( $post );
$custom_text = $post->post_author . ' add the project ' . get_the_title( $item_id );
// WordPress Toolbar
if ( 'string' === $format ) {
$return = apply_filters( 'projectadd_filter', '' . esc_html( $custom_text ) . '', $custom_text, $custom_link );
// Deprecated BuddyBar
} else {
$return = apply_filters( 'projectadd_filter', array(
'text' => $custom_text,
'link' => $custom_link
), $custom_link, (int) $total_items, $custom_text, $custom_title );
}
return $return;
}
}
add_filter( 'bp_notifications_get_notifications_for_user', 'custom_format_buddypress_notifications', 10, 7 );
You've changed the number and order of arguments from the example you linked. The two arguments you added are never used. Restore the arguments in the function to match the example and the the number in your add_filter to 5.
function custom_format_buddypress_notifications( $content, $item_id, $secondary_item_id, $total_items, $format = 'string', $action, $component )
{
...
}
add_filter( 'bp_notifications_get_notifications_for_user', 'custom_format_buddypress_notifications', 10, 7 );
needs to be
function custom_format_buddypress_notifications( $action, $item_id, $secondary_item_id, $total_items, $format = 'string' )
{
...
}
add_filter( 'bp_notifications_get_notifications_for_user', 'custom_format_buddypress_notifications', 10, 5 );

Resources