How to notify through email in wordpress - wordpress

How to notify through email in wordpress when visitor clicks on a link that this link was pressed and/or user ip, city and country was this?
I have given the link a class 'email-link'.

something like this should get you started
// functions.php
// HTML form markup
function mail_form_stuff() {
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
echo '<p><input type="submit" name="send_the_email_to_admin" value="Click this button"></p>';
echo '</form>';
}
// make sure the email will allow for html -- not just plain text
add_filter( 'wp_mail_content_type', 'send_the_email_to_admin_content_type' );
function send_the_email_to_admin_content_type() {
return 'text/html';
}
// if the button is clicked, send the email
function deliver_mail_link_stuff() {
$admin_email = get_option( 'admin_email' );
if ( isset($_POST["send_the_email_to_admin"]) ) {
$_user = wp_get_current_user();
$_name = esc_html( $_user->user_firstname );
$_email = esc_html( $_user->user_email );
$to = $admin_email;
$subject = "Some person clicked my link";
$message = 'Hey this person clicked on that button'.'<br>';
$message .= "the persons email address was: $_email";
$headers[] = "From: $_name <$_email>" . "\r\n";
// $headers[] = "Bcc: John Smith <jsmith#gmail.com>" . "\r\n";
// If everything worked -- display a success message
if ( wp_mail( $to, $subject, $message, $headers ) ) {
echo '<p>sent</p>';
} else {
echo 'An unexpected error occurred';
}
// reset wp_mail_content_type
remove_filter( 'wp_mail_content_type', 'send_the_email_to_admin_content_type' );
}
}
function add_short_code_stuff() {
ob_start();
deliver_mail_link_stuff();
mail_form_stuff();
return ob_get_clean();
}
add_shortcode( 'EMAIL_BUTTON', 'add_short_code_stuff' );
this will add a short code for you
you can then call the shortcode in your theme with
echo do_shortcode('[EMAIL_BUTTON]');

You can't do this as a direct consequence of WordPress since a link is HTML and has no correlation to or integration with anything controlled or processed directly by WordPress. WordPress is merely a structure/processes through which you can add info to a database and then later retrieve it.
If you question is actually meant in a more generic and not specifically wordPress sense, then the answer is any number of ways. You could for example create some JQuery or JS that would add that info everytime a link was clicked. But, you would need to interact with the page headers to try and get all the required info.
But, why bother doing that when a free & arguably market leading tool that does this is already available?
The logical process to this is to use Google Analytics (or a rival tool) as this already collects this kind of info with very little work required to set it up. If you want more specific "event" triggered data (eg a link is clicked), then you can also do this fairly easily too.
https://analytics.google.com
UPDATE
In your comment, you clarify that you want a real time email to be sent to you when a link is clicked, and thus analytics isn't going to fit the bill. In that case you will need to do some work using JQuery & AJAX.
In simple terms you'll need to do something this:
1) Create some JQuery to intercept the url of the link clicked
2) Pass the link (and header info) to a function via an AJAX call
3) Process the header data / send the email
4) Redirect user to the url passed from the link
Here's a tutorial on creating a simple AJAX process in WordPress: https://www.makeuseof.com/tag/tutorial-ajax-wordpress/

Related

WordPress shortcode to display message based on value used by plugin

I'm hoping someone can clue me in on how I can extract a plugin value and display it on my page using a short code. Specifically, when a user reaches the max allowable limit, I would like a notification message to appear on the page (in addition to its placement in a popup) Many tests and I have not been able to get this to work. MANY thanks in advance.
public function add_error_limit_message() {
if ( ! $this->limit_reached ) {
return;
}
$message = apply_filters( 'woocompare_limit_reached_message', __( 'You have reached the maximum number of products for compare table.', 'woocommerce-compare' ) );
echo '<div class="woocompare-error"><p>' . wp_kses_post( $message ) . '</p></div>';
}
add_shortcode( 'limit-reached-message', 'add_error_limit_message' );
Your shortcode function should return the text string you want to insert in place of the shortcode, not echo it.
To track down "critical errors" (php errors) turn on WP_DEBUG and WP_DEBUG_DISPLAY in your wp-config.php file. And try installing and activating the Query Monitor plugin. These will tell you enough about your php errors to track them down and fix them.

How to add verified badge in front of author name across wordpress blog

Good Day,
I have been trying to add verification badge to WordPress users but I no success. I tried using administrator to do the testing by checking if user has role administrator and trying to enter code here update_user_meta (display_name) but I wasn't able to add icons to the display name.
I have as well tried creating a custom field in user profile called verify_user (text field) .... In which I entered the value "verified" and saved ... I have been searching for hooks to use but haven't seen one. I'm not sure which hook/filter to use here
Please is there any solution to adding this verification icon to author's display name in which when the word "verified" is entered into the custom field created in user profile or any other approach available (e.g if user has specific role). I don't mind if the little structure I wrote above would be changed.
Thanks
I was able to get a solution which worked exactly as i wanted. For anyone who might have same task to tackle;
function add_verification_bagdge_to_authors($display_name) {
global $authordata;
if (!is_object($authordata))
return $display_name;
$icon_roles = array(
'administrator',
'verified_author',
);
$found_role = false;
foreach ($authordata->roles as $role) {
if (in_array(strtolower($role), $icon_roles)) {
$found_role = true;
break;
}
}
if (!$found_role)
return $display_name;
$result = sprintf('%s <i title="%s" class="fa fa-check-circle"></i>',
$display_name,
__('This is a Verified Author', 'text-domain-here')
);
return $result;
}
add_filter( 'the_author', 'add_verification_bagdge_to_authors' );
The way i was able to tackle this was to create a user role called Verified Author (using add_role() function from Wordpress Codex ), which will be the role assigned to verified author across the website. All Users with Admin Role are automatically Verified while user role has to be switched from either contributor/Author role to Verified Author.
The above code was able to do 98% of the task but when a verified author / administrator comments, their display name doesn't show the verified badge. I was able to use the below code to fix that (combining the code with a shortcode).
function my_comment_author( $author = '' ) {
// Get the comment ID from WP_Query
$comment = get_comment( $comment_ID );
if ( ! empty($comment->comment_author) ) {
if (!empty($comment->user_id)){
$user=get_userdata($comment->user_id);
$author=$user->display_name.' '. do_shortcode('[this_is_verified-sc]'); // This is where i used the shortcode
} else {
$author = $comment->comment_author;
}
} else {
$author = $comment->comment_author;
}
return $author;
}
add_filter('get_comment_author', 'my_comment_author', 10, 1);
Shortcode to return the Verified Badge if user is admin or verified author
function add_verification_bagdge_to_authors_sc($display_name) {
global $authordata;
if (!is_object($authordata))
return $display_name;
$icon_roles = array(
'administrator',
'verified_author',
);
$found_role = false;
foreach ($authordata->roles as $role) {
if (in_array(strtolower($role), $icon_roles)) {
$found_role = true;
break;
}
}
if (!$found_role)
return $display_name;
$result = sprintf('%s <i title="%s" class="fa fa-check-circle"></i>', $display_name, __('This is a Verified Author', 'text-domain-here') );
return $result;
}
add_shortcode( 'this_is_verified-sc', 'add_verification_bagdge_to_authors_sc' );
Please Note: Not all Magazine theme are properly coded / have a hard coded Block and module elements, so the verified badge might not work on their block / module element. I experienced this during the whole website design process, so we had to change up theme and the only modification i had to make to the new theme was to remove the html escape added to their block/module code, so that the icon can be rendered. i.e. in their module/block code they had something like this esc_html( the_author() ) and i removed the esc_html to have just the_author() an it all worked.
Its not really a straight forward solution but that is how i was able to tackle the task without using a plugin. Just add the codes to your functions.php file and that's it. I hope it helps someone.
Thanks to Kero for pointing me in the right direction, providing the code i was able to work with and manipulate

handling response and placing order in woocommerce after redirecting back from payment website

I am developing a payment gateway plugin (For Cybersource Payment) for WooCommerce. I developed it to almost at the end, but one thing is intercepting me to finish and that is the part after redirecting from payment gateway website after successful payment back to my wordpress page (Purchase Confirmation Page - New Wordpress Page created using template in wp-content/themes/my-theme/order-confirm-template.php). But i dont know how to handle the response coming back from payment website. I looked for some woocommerce hooks but nothing worked. I found there is a hook woocommerce_thankyou but that is also not working for me.
Can somebody help me out here in these two points below
1) How to handle response and placed the order properly and remove the items from the cart when coming back after successful payment from gateway website.
2) which page should i redirect back from gateway website? back to the same checkout page or some custom page just like i did.
Any Help with code will be very appreciated. Thanks.
I have used the following code in my plugin, I hope this works for you too :)
First add this code,
function receipt_page($order){
echo $this -> ResponceHandler($order);
}
Now the code for ResponceHandler($order) function,
public function ResponceHandler($order_id){
if(!isset($_POST['ResponseCode'])){
global $woocommerce;
echo '<p>'.__('Thank you for your order, please click the button below to pay with XYZ', 'woocommerce').'</p>';
$order = new WC_Order($order_id);
$order_id = $order_id.'_'.date("ymds");
$post_data = get_post_meta($order_id,'_post_data',true);
update_post_meta($order_id,'_post_data',array());
###Your Form Code HERE###
echo '<form><input value="Proceed To Payment" type="submit" /> </form>';
}
###Haandle the response###
if(isset($_POST['ResponseCode']))
{
if($_POST['ResponseCode']==0){
global $woocommerce;
session_start();
$_SESSION['post']=$_POST;
$order = new WC_Order($order_id);
$order_id = $order_id.'_'.date("ymds");
$post_data = get_post_meta($order_id,'_post_data',true);
update_post_meta($order_id,'_post_data',array());
if($order->status != 'processing'){
$order ->status ='Processing';
$order->payment_complete();
$order -> add_order_note('XYZ Payment Gateway <br>Response message :'.$_POST['ResponseMessage'].'<br>Payment ID :'.$_POST['PaymentID'].'<br>Merchant Reference Number :'.$_POST['MerchantRefNo'].'<br>Transaction ID :'.$_POST['TransactionID'].'');
add_post_meta( $order->id, '_paymentid', sanitize_text_field( $_POST['PaymentID'] ) );
add_post_meta( $order->id, '_trno', sanitize_text_field( $_POST['TransactionID'] ) );
$woocommerce -> cart -> empty_cart();
wp_redirect( $order->get_checkout_order_received_url());
}
}
else {
if($order->status != 'failed'){
$order ->status ='failed';
echo "Payment failed!<br><br><br>Possible Error : ".$_POST['ResponseMessage']."<br>PaymentID: ".$_POST['PaymentID']."<br><br><br>We request you to save these details for further reference. <br>You can always pay for this order by clicking on your name in the top right corner and visiting your orders section."; }
}
}
}

Wordpress shortcode linked to another DB

First thing first, this is my first shortcode attempt.
It is worthed mention that I'm also using woocommerce on my website.
Let's start:
I know that to add shortcodes into wordpress, you need to write something similar to the code below into the functions.php file: (this is just an example)
function myshortcode() {
return "This is a shortcode example!";
}
add_shortcode( 'mycode', 'myshortcode' );
and if i add [mycode] into the wordpress page editor, the preview shows my text correctly.
But what if i need to use a variable (in my case woocommerce order number) in the shortcode?
Let's say i need to compare woocommerce_order_number with my_custom_uid (inserted into another database, outside wordpress).
I usually use a db request like the one below, and usually it works fine (as before, this is only an example):
select 'my_custom_uid' from 'my_custom_database' where 'woocommerce_order_number' = '1234'
The problem is that i don't know the woocommerce_order_number (it changes everytime!), because this shortcode needs to go inside an html email body i need to send out to customers after they placed the order.
How can i get the customer woocommerce order (variable that changes everytime) so that i will be able to use it into my shortcode to link it to my custom_uid?
If the question is not clear enough, please feel free to ask for clarification!
thanks a lot
I don't see a reason to use a shortcode. If you want to add something to an email, you should use one of the hooks in the email. For example:
function kia_display_email_order_meta( $order, $sent_to_admin, $plain_text ) {
$some_field = get_post_meta( $order->id, '_some_field', true ),
$another_field = get_post_meta( $order->id, '_another_field', true ),
if( $plain_text ){
echo 'The value for some field is ' . $some_field . ' while the value of another field is ' . $another_field;
} else {
echo '<p>The value for <strong>some field</strong> is ' . $some_field. ' while the value of <strong>another field</strong> is ' . $another_field . '</p>';
}
}
add_action('woocommerce_email_customer_details', 'kia_display_email_order_meta', 30, 3 );
Note that the $order object is the first parameter available to the kia_display_email_order_meta function. So you'd be able to get the ID via $order->id. This should add the data after the customer address details, but there are other hooks available if woocommerce_email_customer_details isn't appropriate.
I finally managed to solve this, and here's what i did if someone is interested:
<?PHP
add_action('fue_before_variable_replacements', 'register_variable_replacements', 11, 4);
add_action('fue_email_variables_list', 'email_variables_list');
/**
* This gets called to replace the variable in the email with an actual value
* #param $var - Modify this: array key is the variable name, value is the replacement
*/
function register_variable_replacements($var, $email_data, $queue_item, $email){
global $wpdb;
// Look up UID from order number
$orderNumber = $var->get_variables()['order_number'];
$sql = " //Your sql statement here...//";
$results = $wpdb->get_results($sql);
$UID = $results[0]->meta_value;
$variables = array(
'uid' => $UID
);
$var->register($variables);
}
function email_variables_list($email)
{
global $woocommerce;
?>
<li class="var hideable var_subscriptions">
<strong>{uid}</strong>
<img class="help_tip" title="<?php _e('Order UID', 'follow_up_emails'); ?>" src="<?php echo $woocommerce->plugin_url(); ?>/assets/images/help.png" width="16" height="16"/>
</li>
<?php
}
Now on your follow up email plugin, you can use {uid} as a variable and this will be replaced with the correct value on every email.
I though the best way was to use short code, but then i discovered this filter and i think this is the best way to handle this. This code is also pretty flexible and you can add as many variables as you want.
Hope this can help someone.

WordPress Plugin: Call function on button click in admin panel

I need to create a WordPress plugin that calls a PHP function when a button in an admin panel is clicked. I've been looking at tutorials for writing basic WordPress plugins and adding admin panels but I still don't understand how exactly to register a button to a specific function in my plug-in.
Here's what I have so far:
/*
Plugin Name:
Plugin URI:
Description:
Author:
Version: 1.0
Author URI:
*/
add_action('admin_menu', 'wc_plugin_menu');
function wc_plugin_menu(){
add_management_page('Title', 'MenuTitle', 'manage_options', 'wc-admin-menu', 'wc_plugin_options');
}
function wc_plugin_options(){
if (!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient permissions to access this page.') );
}
echo '<div class="wrap">';
echo '<button>Call Function!</button>'; //add some type of hook to call function
echo '</div>';
}
function button_function()
{
//do some stuff
}
?>
Although the answers on this page provided a useful start, it took a while for me to figure out how to get option (2) working. Given this, the following code might be of help to some people.
If you create a plugin with the following code and it will add a left hand menu option called 'Test Button' when you are in the admin area. Click on this and you will see a button. Clicking that button runs the test_button_action function. In my example function I've both put a message on the page and written to a log file.
<?php
/*
Plugin Name: Example of Button on Admin Page
Plugin URI:
Description:
Author:
Version: 1.0
Author URI:
*/
add_action('admin_menu', 'test_button_menu');
function test_button_menu(){
add_menu_page('Test Button Page', 'Test Button', 'manage_options', 'test-button-slug', 'test_button_admin_page');
}
function test_button_admin_page() {
// This function creates the output for the admin page.
// It also checks the value of the $_POST variable to see whether
// there has been a form submission.
// The check_admin_referer is a WordPress function that does some security
// checking and is recommended good practice.
// General check for user permissions.
if (!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient pilchards to access this page.') );
}
// Start building the page
echo '<div class="wrap">';
echo '<h2>Test Button Demo</h2>';
// Check whether the button has been pressed AND also check the nonce
if (isset($_POST['test_button']) && check_admin_referer('test_button_clicked')) {
// the button has been pressed AND we've passed the security check
test_button_action();
}
echo '<form action="options-general.php?page=test-button-slug" method="post">';
// this is a WordPress security feature - see: https://codex.wordpress.org/WordPress_Nonces
wp_nonce_field('test_button_clicked');
echo '<input type="hidden" value="true" name="test_button" />';
submit_button('Call Function');
echo '</form>';
echo '</div>';
}
function test_button_action()
{
echo '<div id="message" class="updated fade"><p>'
.'The "Call Function" button was clicked.' . '</p></div>';
$path = WP_TEMP_DIR . '/test-button-log.txt';
$handle = fopen($path,"w");
if ($handle == false) {
echo '<p>Could not write the log file to the temporary directory: ' . $path . '</p>';
}
else {
echo '<p>Log of button click written to: ' . $path . '</p>';
fwrite ($handle , "Call Function button clicked on: " . date("D j M Y H:i:s", time()));
fclose ($handle);
}
}
?>
Well, you have two options.
1) Use AJAX to create an admin-ajax hook that you execute with JavaScript when the user clicks the button. You can learn about that approach here: http://codex.wordpress.org/AJAX (make sure to add a nonce for security ( http://codex.wordpress.org/WordPress_Nonces )). This is also a good resource for creating admin-ajax hooks: http://codex.wordpress.org/AJAX_in_Plugins
2) Put the button in a form, POST that form to your plugin and add some code to handle the POST'd form (if you do this, make sure you include a nonce for security ( http://codex.wordpress.org/WordPress_Nonces ) and also make sure that the user trying to click the button has the right privileges to do so http://codex.wordpress.org/Function_Reference/current_user_can
What you're trying to do is not super-complex, but it does involve a good understanding of forms, PHP, and (maybe) JavaScript. If your JavaScript is ok, I'd recommend option 1, since it doesn't require the user to reload the page.

Resources