Generate WooCommerce coupon when comment review is approved - wordpress

I'm trying to generate a coupon code for customer once his review comment in woocommerce product is approved. I have the whole code ready but once comment is approved nothing happen.
My code only works with comment_post hook but not with the comment_unapproved_to_approved hook. Any advice?
function action_comment_post_coupon( $comment, $comment_ID, $comment_approved, $commentdata ) {
if ( isset ( $commentdata['comment_author_email'] ) ) {
// Get author email
$author_email = $commentdata['comment_author_email'];
if ( is_email( $author_email ) ) {
$value = random_int(100000, 999999);
$customer = $comment->comment_author_email;
$coupon_code = $value; // Code
$amount = '20'; // Amount
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
update_post_meta( $new_coupon_id, 'customer_email', $author_email );
update_post_meta( $new_coupon_id, 'product_ids',$product_ids );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '1' );
update_post_meta( $new_coupon_id, 'expiry_date', strtotime("+14 days") );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
unset($product_ids);
}
}
}
add_action( 'comment_unapproved_to_approved', 'action_comment_post_coupon', 10, 4 );

"My code only works with comment_post hook but not with the comment_unapproved_to_approved hook"
As you can see the comment_post hook contains 3 params
/**
* Fires immediately after a comment is inserted into the database.
*
* #since 1.2.0
* #since 4.5.0 The `$commentdata` parameter was added.
*
* #param int $comment_ID The comment ID.
* #param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam.
* #param array $commentdata Comment data.
*/
function action_comment_post( $comment_ID, $comment_approved, $commentdata ) {
// Do something
}
add_action( 'comment_post', 'action_comment_post', 10, 3 );
See: do_action( 'comment_post', int $comment_ID, int|string $comment_approved, array $commentdata )
While the comment_unapproved_to_approved hook contains only 1 which is $comment, therefore just changing hookname is not enough.
See: do_action( "comment_{$old_status}_to_{$new_status}", WP_Comment $comment )
So to answer your question you get:
/**
* Fires when the comment status is in transition from one specific status to another.
*
* The dynamic portions of the hook name, `$old_status`, and `$new_status`,
* refer to the old and new comment statuses, respectively.
*
* Possible hook names include:
*
* - `comment_unapproved_to_approved`
* - `comment_spam_to_approved`
* - `comment_approved_to_unapproved`
* - `comment_spam_to_unapproved`
* - `comment_unapproved_to_spam`
* - `comment_approved_to_spam`
*
* #since 2.7.0
*
* #param WP_Comment $comment Comment object.
*/
function action_comment_unapproved_to_approved( $comment ) {
// When isset
if ( isset ( $comment->comment_author_email ) ) {
// Get author email
$author_email = $comment->comment_author_email;
// Is email
if ( is_email( $author_email ) ) {
// Get an emty instance of the WC_Coupon Object
$coupon = new WC_Coupon();
// Generate a non existing coupon code name
$coupon_code = random_int( 100000, 999999 ); // OR generate_coupon_code();
$discount_type = 'percent';
$coupon_amount = '20'; // Amount
// Set the necessary coupon data (since WC 3+)
$coupon->set_code( $coupon_code );
$coupon->set_discount_type( $discount_type );
$coupon->set_amount( $coupon_amount );
$coupon->set_individual_use( true );
$coupon->set_usage_limit( 1 );
$coupon->set_email_restrictions( array( $author_email ) );
$coupon->set_date_expires( strtotime( '+14 days' ) );
$coupon->set_free_shipping( true );
// Create, publish and save coupon (data)
$coupon->save();
}
}
}
add_action( 'comment_unapproved_to_approved', 'action_comment_unapproved_to_approved', 10, 1 );
Note: since WooCommerce 3, your code is a bit outdated. Instead you should better use the available WC_Coupon setter methods.
All information about this can be found via WC_Coupon

Related

Keep encoded link after order is completed in wordpress

Hey guys is there a way to keep encoded link after order is completed in wordpress?
It looks good in cart and checkout:
link
But not so good in order review and admin order review
link
I use encodeURIComponent to encode every url param:
My example link that i generate
EDIT
Product creation page: https://isodos.lt/produktas/pinigine/ If you want to see order review page you can add it to the cart and test buy it with random name etc.
Btw, i took php code from somewhere, not my code, im not good with php, especially in wordpress
//small example
const graviravimasFinished = document.querySelector("#iconic-engraving-finished");
if(tf1text === "nerNieko" || tf1text === ""){
tf1TxtFinal = "";
}else{
let txt1TxtEncoded = encodeURIComponent(tf1text);
tf1TxtFinal = `&tf1inner=${txt1TxtEncoded}`;
}
tf1TxtFinal = `${tf1TxtFinal}${tf1TopFinal}${tf1LeftFinal}${tf1SizeFinal}${tf1FontFinal}`;
tf2TxtFinal = `${tf2TxtFinal}${tf2TopFinal}${tf2LeftFinal}${tf2SizeFinal}${tf2FontFinal}`;
tf3TxtFinal = `${tf3TxtFinal}${tf3TopFinal}${tf3LeftFinal}${tf3SizeFinal}${tf3FontFinal}`;
graviravimasFinished.value = `Stilius`;
<?php
function iconic_output_engraving_field() {
global $product;
if ( $product->get_id() !== 5296 ) {
return;
}
?>
<!-- Graviravimo tekstas -->
<div style="padding-bottom: 10px" class="iconic-engraving-field">
<!-- Info -->
<input style="display: none;" type="text" id="iconic-engraving-finished" name="iconic-engraving-finished">
</div>
<?php
}
add_action( 'woocommerce_before_add_to_cart_button', 'iconic_output_engraving_field', 10 );
/**
* Add engraving text to cart item.
*
* #param array $cart_item_data
* #param int $product_id
* #param int $variation_id
*
* #return array
*/
function iconic_add_engraving_text_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
$engraving_text = filter_input( INPUT_POST, 'iconic-engraving-finished' );
if ( empty( $engraving_text ) ) {
return $cart_item_data;
}
$cart_item_data['iconic-engraving-finished'] = $engraving_text;
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'iconic_add_engraving_text_to_cart_item', 10, 3 );
/**
* Display engraving text in the cart.
*
* #param array $item_data
* #param array $cart_item
*
* #return array
*/
function iconic_display_engraving_text_cart( $item_data, $cart_item ) {
if ( empty( $cart_item['iconic-engraving-finished'] ) ) {
return $item_data;
}
$item_data[] = array(
'key' => __( 'Graviravimas', 'iconic-finished' ),
'value' => $cart_item['iconic-engraving-finished'] ,
'display' => '',
);
return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'iconic_display_engraving_text_cart', 10, 2 );
/**
* Add engraving text to order.
*
* #param WC_Order_Item_Product $item
* #param string $cart_item_key
* #param array $values
* #param WC_Order $order
*/
function iconic_add_engraving_text_to_order_items( $item, $cart_item_key, $values, $order ) {
if ( empty( $values['iconic-engraving-finished'] ) ) {
return;
}
$item->add_meta_data( __( 'Graviravimas', 'iconic-finished' ), $values['iconic-engraving-finished'] );
}
add_action( 'woocommerce_checkout_create_order_line_item', 'iconic_add_engraving_text_to_order_items', 10, 4 );

Woocommerce - Calculate Exta Fee Based on Amount of People

I've added in a function for a custom field on the product general options:
// Add Custom Field to Product under General
function create_extra_fee_field() {
$args = array(
'id' => 'park_fee',
'label' => __( 'Natl Park Entrance Fee', 'tranq-lsx-child' ),
'class' => 'tranq-custom-field',
'desc_tip' => true,
'description' => __( 'This sets the Fee that will be added to the car.', 'tranq-lsx-child' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'create_extra_fee_field' );
// Save Custom Field Data
function save_extra_fee_field( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['park_fee'] ) ? $_POST['park_fee'] : '';
$product->update_meta_data( 'park_fee', sanitize_text_field( $title ) );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'save_extra_fee_field' );
I would like to add this as an extra fee to the Cart Totals which multiplied based on the amount of Person/People that were selected from the Woocommerce Bookings.
Something like this:
// Calculate Extra Fee Based on Amount of People.
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
function add_custom_fees( WC_Cart $cart ){
$park_fee = get_post_meta($item['product_id'] , 'park_fee', true);
foreach( $cart->get_cart() as $item ){
$fees += $item[ 'park_fee' ] * 14706;
}
if( $fees != 0 ){
$cart->add_fee( 'Park Fee', $fees);
}
}
How do I go about in achieving this? Any Links to a walkthrough would be greatly appreciated.
I've added this and it seems to work:
// Add Custom Field to Cart Totals
function woo_add_cart_fee() {
global $woocommerce;
foreach( WC()->cart->get_cart() as $cart_item ){
// Get the WC_Product object (instance)
$product = $cart_item['data'];
$product_id = $product->get_id(); // get the product ID
$custom_field_value = get_post_meta( $product->get_id(), 'park_fee', true );
$person = array_sum( $cart_item['booking']['_persons'] );
}
$additional_fee_name = "Natl Park Entrance Fee";
$extra_fee = $custom_field_value * $person;
$addedFee = false;
// first check to make sure it isn’t already there
foreach ( $woocommerce->cart->get_fees() as $_fee )
{
if ($_fee->id == sanitize_title($additional_fee_name) )
{
$_fee->amount = (float) esc_attr( $extra_fee );
}
}
if (!$addedFee)
{
$woocommerce->cart->add_fee( __($additional_fee_name, "woocommerce"),
$extra_fee, $additional_fee_taxable );
}
}
add_action( "woocommerce_before_calculate_totals", "woo_add_cart_fee" );

Update Order Programmatically Doesn't Update Totals

I'm trying to update the quantities of an ordered product and when doing so I would like the order to reflect the actual cost. What I find happens is that the Product Cost is reduced to match the total and the order total is never actually updated. I've supplied a simple sample below:
function prefix_update_woo_order() {
$order_id = 123; // This needs to be a real order or there will be errors
$order_item_id = 5; // This needs to be a real order item ID or there will be errors.
$order = new WC_Order( $order_id );
$order_items = $order->get_items();
$order_items[ $order_item_id ]->set_quantity( 2 );
$order->calculate_taxes();
$order->calculate_totals();
$order->save();
}
add_action( 'admin_init', 'prefix_update_woo_order' );
For example, a "Beanie with Logo" product is on sale for $18.00 and I originally buy 1. I want to programmitically update the order item to a quantity of 2 instead of 1 after the order has been placed. I would expect the total to be $36.00 but what I'm finding is that the product cost changes to match the total price. Instead of a cost of $18.00 for a "Beanie with Logo" the quantity is updated to 2 and the cost is reduced to $9.00ea.
In short, what I want to do is update an existing order items quantity and have the totals updated to reflect the new quantity cost, discount, taxes. What methods do I need to use to achieve this?
Hello I think this code will change your problem
add_action( 'admin_init', 'test_order_update_order' );
function test_order_update_order() {
$order_id = 80; // This needs to be a real order or there will be errors
$order_item_id = 11; // This needs to be a real order item ID or there will be errors.
$quantity = 2; //quantity which you want to set.
$order = new WC_Order( $order_id );
$order_items = $order->get_items();
foreach ( $order_items as $key => $value ) {
if ( $order_item_id == $key ) {
$product_value = $value->get_data();
$product_id = $product_value['product_id'];
}
}
$product = wc_get_product( $product_id );
$price = $product->get_price();
$price = ( int ) $quantity * $price;
$order_items[ $order_item_id ]->set_quantity( 2 );
$order_items[ $order_item_id ]->set_subtotal( $price );
$order->calculate_taxes();
$order->calculate_totals();
$order->save();
}
i have not tried what you are trying to achieve before. What i see in your code is that $order_items is an array of Items Objects produced from WC_Order::get_items(), but i dont see the WC_Order Instance being notified that the order items have changed. I would expect a method like $order->update_cart($order_items); I believe i found some usefull links for more research
https://hotexamples.com/examples/-/WC_Order/-/php-wc_order-class-examples.html
woocommerce - programmatically update cart item quantity
Sorry, i was not much of help!
Use the follows code snippet to do the above task -
function prefix_update_woo_order() {
$order_id = 123; // This needs to be a real order or there will be errors
$order_item_id = 5; // This needs to be a real order item ID or there will be errors.
$order = wc_get_order( $order_id );
if( $order && !wc_get_order_item_meta( $order_item_id, '_order_item_data_updated', true ) ) {
$item_price = wc_get_order_item_meta( $order_item_id, '_line_total', true );
$updated_item_quantity = 2;
wc_update_order_item_meta( $order_item_id, '_qty', $updated_item_quantity );
wc_update_order_item_meta( $order_item_id, '_line_total', $item_price * $updated_item_quantity );
$order->calculate_totals();
$order->save();
// set flag
wc_add_order_item_meta( $order_item_id, '_order_item_data_updated', true, true );
}
}
add_action( 'admin_init', 'prefix_update_woo_order' );
Codes goes to your active theme's functions.php
This is what I've come up with. I've tried to use the wc_format_decimal() where applicable. Seems like a lot of work to simply update an order items quantity but it is what it is.
The bottom comment is unnecessary but if you're using the Cost of Goods plugin then that will take care of that.
/**
* Update the order item quantity and totals
* #param Integer $order_id
* #param Integer $order_item_id
* #param Integer $quantity - Quantity to set
*
* #return void
*/
function prefix_update_woo_order( $order_id, $order_item_id, $quantity ) {
// Get Order, Item, and Product Data
$order = new WC_Order( $order_id );
$order_items = $order->get_items();
$line_item = $order_items[ $order_item_id ];
$variation_id = $line_item->get_variation_id();
$product_id = $line_item->get_product_id();
$product = wc_get_product( $variation_id ? $variation_id : $product_id );
$quantity_old = $line_item->get_quantity();
// Calculate Old and New Discounts
$discount = wc_format_decimal( $line_item->get_subtotal() - $line_item->get_total(), '' );
if( ! empty( $discount ) ) {
$discount_per_qty = wc_format_decimal( ( $discount / $quantity_old ), '' );
$discount = wc_format_decimal( ( $discount_per_qty * $quantity ), '' );
}
// Set Quantity and Order Totals
$line_item->set_quantity( $quantity );
$total = wc_get_price_excluding_tax( $product, array( 'qty' => $line_item->get_quantity() ) ); // Also see `wc_get_price_excluding_tax()`
$line_item->set_subtotal( $total ); // Without Discount
$line_item->set_total( $total - $discount ); // With Discount
// Save Everything
$line_item->save();
wc_save_order_items( $order_id, $order_items );
/**
* If using the 'Cost of Goods' Plugin
* - - - - - -
* $cog = $line_item->get_meta( '_wc_cog_item_cost', true );
* $new_cog = wc_format_decimal( ( $quantity * $cog ), '' );
* $line_item->update_meta_data( '_wc_cog_item_total_cost', $new_cog );
* wc_cog()->set_order_cost_meta( $order_id, true );
*/
}

Woocommerce action hook to execute function on subscription renewal

I want to know if there is a action hook that can check if the subscription is successfully renewed in woocommerce ? BTW I am using woocommerce subscription plugin. I have created a functionality that records the date of the subscription order and add it to a CSV file, the function is working perfectly for the first purchase I mean when the user purchase a subscription it is recorded successfully in the CSV because I am firing up the function on woocommerce_thankyou action hook, The only issue I am facing is that I can't seem to find a hook which can execute this function on successful subscription renewal. I tried to use woocommerce_subscription_renewal_payment_complete action hook but it didn't worked below is the function that I have created.
/**
* Add subscriptions to csv.
*/
add_action( 'woocommerce_subscription_renewal_payment_complete', 'add_subs_to_csv' );
add_action( 'woocommerce_thankyou', 'add_subs_to_csv' );
function add_subs_to_csv( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ( $items as $key => $value ) {
$meta_values = $value->get_data();
foreach ( $meta_values as $meta_key => $meta_value ) {
if ( $meta_key == 'product_id' && $meta_value == 875 ) {
$paid_date = explode( " ", get_post_meta( $order_id, '_paid_date', true ) );
$subs_paid_date = date( 'd F, Y', strtotime( $paid_date[0] ) );
wc_add_order_item_meta( $key, 'Delivery Date', $subs_paid_date );
}
}
}
}
Could the wcs_renewal_order_created hook be what you're looking for? The docs say:
WooCommerce Subscriptions stores all details of each subscription
renewal in a standard WooCommerce order, only with a special meta flag
linking it to a subscription.
These orders are always created through the wcs_create_renewal_order()
function, regardless of whether they are created for a scheduled
renewal event, manually via the WooCommerce > Edit Subscription
administration screen, or via the Subscriptions endpoints for the
WooCommerce REST API. Because of this, it’s possible to add, remove or
update the value of anything on that renewal order using this filter.
For example, this can be used to add a discount to specific renewal
orders, like the 12th order each year. It could also be used to add
one-time fee for a certain renewal order, like a special annual extra
fee on a monthly subscription.
So the above hook should trigger after payment, you'd probably just need to check if it was completed status which you could also do in your current hooks:
/**
* After WooCommerce Subscriptions Creates Renewal Order
*
* #param WC_Order Object $order
* #param Integer|WC_Subscription Object $subscription
*
* #return WC_Order $order
*/
function add_subs_to_csv( $order, $subscription ) {
if( 'completed' === $order->get_status() ) {
$items = $order->get_items();
foreach ( $items as $key => $value ) {
$meta_values = $value->get_data();
foreach ( $meta_values as $meta_key => $meta_value ) {
if ( $meta_key == 'product_id' && $meta_value == 875 ) {
$paid_date = explode( " ", get_post_meta( $order_id, '_paid_date', true ) );
$subs_paid_date = date( 'd F, Y', strtotime( $paid_date[0] ) );
wc_add_order_item_meta( $key, 'Delivery Date', $subs_paid_date );
}
}
}
}
return $order
}
add_filter( 'wcs_renewal_order_created', 'add_subs_to_csv', 10, 2 );
I had a issue at Subscription renewal and I got it fixed with below code:
/*
* FIXED : Membership got PAUSED everytime at automatic subscription renewal
*/
function change_membership_status_active( $subscription , $order ) {
global $wpdb;
if( 'completed' === $order->get_status() ) {
$membership = $wpdb->get_row( "SELECT * FROM wp_postmeta WHERE meta_key = '_subscription_id' AND meta_value = $subscription->ID" );
$mem_id = $membership->post_id;
$status = 'wcm-active';
$update_args = array( 'ID' => $mem_id, 'post_status' => $status );
wp_update_post($update_args);
}
}
add_action( 'woocommerce_subscription_renewal_payment_complete', 'change_membership_status_active', 10, 2 );

How do you create a basic Wordpress admin pointer?

I have been looking around for quite awhile now and all I have found are tutorials from 3-4 years ago that explain how to do a pointer tour. All I want to do is add a pointer that pops up when someone activates my plugin so that I can notify them of a new menu option where they will go to view my plugin settings. Any help would be greatly appreciated!
Pointers in WP need 3 components:
1: wp-pointer css file
2: wp-pointer JS file
3: A JavaScript snippet
To 1 and 2
include them simply with:
wp_enqueue_style( 'wp-pointer' );
and
wp_enqueue_script( 'wp-pointer' );
The JS code:
<script type="text/javascript">
(function($){
var options = {"content":"<h3>Personal Data and Privacy<\/h3><h4>Personal Data Export and Erasure<\/h4><p>New <strong>Tools<\/strong> have been added to help you with personal data export and erasure requests.<\/p><h4>Privacy Policy<\/h4><p>Create or select your site’s privacy policy page under <strong>Settings > Privacy<\/strong> to keep your users informed and aware.<\/p>","position":{"edge":"left","align":"bottom"},"pointerClass":"wp-pointer arrow-bottom","pointerWidth":420}, setup;
if ( ! options )
return;
options = $.extend( options, {
close: function() {
$.post( ajaxurl, {
pointer: 'wp500_isrc_pointer',
action: 'dismiss-wp-pointer'
});
}
});
setup = function() {
$('#menu-settings').first().pointer( options ).pointer('open');
};
if ( options.position && options.position.defer_loading )
$(window).bind( 'load.wp-pointers', setup );
else
$(document).ready( setup );
})( jQuery );
</script>
Of Course you need to wrap all them in a php file to check the user capabilities and check the dismiss from the users meta.
I have copied the WP pointer class in wp-admin/includes/class-wp-internal-pointers and made a custom one from it.
Here the complete code which i can call it with an action hook like:
add_action( 'admin_enqueue_scripts', array( 'isrc_Internal_Pointers', 'enqueue_scripts') );
add_action( 'user_register',array( 'isrc_Internal_Pointers', 'dismiss_pointers_for_new_users' ) );
The Full PHP file (include it in your code and call the 2 actions):
<?php
/**
* Administration API: WP_Internal_Pointers class
*
* #package WordPress
* #subpackage Administration
* #since 4.4.0
*/
/**
* Core class used to implement an internal admin pointers API.
*
* #since 3.3.0
*/
final class isrc_Internal_Pointers {
/**
* Initializes the new feature pointers.
*
* #since 3.3.0
*
* All pointers can be disabled using the following:
* remove_action( 'admin_enqueue_scripts', array( 'WP_Internal_Pointers', 'enqueue_scripts' ) );
*
* Individual pointers (e.g. wp390_widgets) can be disabled using the following:
* remove_action( 'admin_print_footer_scripts', array( 'WP_Internal_Pointers', 'pointer_wp390_widgets' ) );
*
* #static
*
* #param string $hook_suffix The current admin page.
*/
public static function enqueue_scripts( $hook_suffix ) {
/*
* Register feature pointers
*
* Format:
* array(
* hook_suffix => pointer callback
* )
*
* Example:
* array(
* 'themes.php' => 'wp390_widgets'
* )
*/
$registered_pointers = array(
'index.php' => 'wp500_isrc_pointer',
);
// Check if screen related pointer is registered
if ( empty( $registered_pointers[ $hook_suffix ] ) )
return;
$pointers = (array) $registered_pointers[ $hook_suffix ];
/*
* Specify required capabilities for feature pointers
*
* Format:
* array(
* pointer callback => Array of required capabilities
* )
*
* Example:
* array(
* 'wp390_widgets' => array( 'edit_theme_options' )
* )
*/
$caps_required = array(
'wp500_isrc_pointer' => array(
'install_plugins'
),
);
// Get dismissed pointers
$dismissed = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );
$got_pointers = false;
foreach ( array_diff( $pointers, $dismissed ) as $pointer ) {
if ( isset( $caps_required[ $pointer ] ) ) {
foreach ( $caps_required[ $pointer ] as $cap ) {
if ( ! current_user_can( $cap ) )
continue 2;
}
}
// Bind pointer print function
add_action( 'admin_print_footer_scripts', array( 'isrc_Internal_Pointers', 'pointer_'.$pointer ) );
$got_pointers = true;
}
if ( ! $got_pointers )
return;
// Add pointers script and style to queue
wp_enqueue_style( 'wp-pointer' );
wp_enqueue_script( 'wp-pointer' );
}
/**
* Print the pointer JavaScript data.
*
* #since 3.3.0
*
* #static
*
* #param string $pointer_id The pointer ID.
* #param string $selector The HTML elements, on which the pointer should be attached.
* #param array $args Arguments to be passed to the pointer JS (see wp-pointer.js).
*/
private static function print_js( $pointer_id, $selector, $args ) {
if ( empty( $pointer_id ) || empty( $selector ) || empty( $args ) || empty( $args['content'] ) )
return;
?>
<script type="text/javascript">
(function($){
var options = <?php echo wp_json_encode( $args ); ?>, setup;
if ( ! options )
return;
options = $.extend( options, {
close: function() {
$.post( ajaxurl, {
pointer: '<?php echo $pointer_id; ?>',
action: 'dismiss-wp-pointer'
});
}
});
setup = function() {
$('<?php echo $selector; ?>').first().pointer( options ).pointer('open');
};
if ( options.position && options.position.defer_loading )
$(window).bind( 'load.wp-pointers', setup );
else
$(document).ready( setup );
})( jQuery );
</script>
<?php
}
/**
* Display a pointer for wp500_isrc_pointer
*
* #since 4.9.6
*/
public static function pointer_wp500_isrc_pointer() {
$content = '<h3>' . __( 'Personal Data and Privacy' ) . '</h3>';
$content .= '<h4>' . __( 'Personal Data Export and Erasure' ) . '</h4>';
$content .= '<p>' . __( 'New <strong>Tools</strong> have been added to help you with personal data export and erasure requests.' ) . '</p>';
$content .= '<h4>' . __( 'Privacy Policy' ) . '</h4>';
$content .= '<p>' . __( 'Create or select your site’s privacy policy page under <strong>Settings > Privacy</strong> to keep your users informed and aware.' ) . '</p>';
if ( is_rtl() ) {
$position = array(
'edge' => 'right',
'align' => 'bottom',
);
} else {
$position = array(
'edge' => 'left',
'align' => 'bottom',
);
}
$js_args = array(
'content' => $content,
'position' => $position,
'pointerClass' => 'wp-pointer arrow-bottom',
'pointerWidth' => 420,
);
self::print_js( 'wp500_isrc_pointer', '#menu-settings', $js_args );
}
/**
* Prevents new users from seeing existing 'new feature' pointers.
*
* #since 3.3.0
*
* #static
*
* #param int $user_id User ID.
*/
public static function dismiss_pointers_for_new_users( $user_id ) {
add_user_meta( $user_id, 'dismissed_wp_pointers', 'wp500_isrc_pointer' );
}
}
What you are looking for is WordPress Activation / Deactivation Hooks. For example:
register_activation_hook( __FILE__, 'pluginprefix_function_to_run' );
And on pluginprefix_function_to_run, display a nice message to let users know that you've added a menu using admin_notices:
function my_admin_notice() {
?>
<div class="updated">
<p><?php _e( 'Your message goes here!', 'my-text-domain' ); ?></p>
</div>
<?php
}
function pluginprefix_function_to_run() {
add_action( 'admin_notices', 'my_admin_notice' );
}

Resources