WordPress Plugin: Call function on button click in admin panel - wordpress

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.

Related

How to notify through email in 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/

Check for logged in users from outside wp page in wordpress

I need to check if the user has logged in to my wordpress site from a non wp page.How can this be done ?
I tried to create a plugin that check for user details and returns logged in details.But when I access the plugin from outside wp.Its always returning 'not loggedin'
This is the code
require('../../wp-blog-header.php');
if (is_user_logged_in()){
echo "Welcome, registered user!";
}
else {
echo "Welcome, visitor!";
};
This always returns "Welcome, visitor!".
Which is the best way for checking this ?
You could use ajax:
Add this in function.php:
function my_ajax_is_user_logged_in() {
// Handle request then generate response using WP_Ajax_Response
if (is_user_logged_in()){
echo "Welcome, registered user!";
}
else {
echo "Welcome, visitor!";
};
exit;
}
add_action( 'wp_ajax_is_user_logged_in', 'my_ajax_is_user_logged_in' );
add_action( 'wp_ajax_nopriv_is_user_logged_in', 'my_ajax_is_user_logged_in' );
Within jquery you can access like this:
$.get('http://yoursite.com/wordpress/wp-admin/admin-ajax.php',function(data,status){
alert(data);
});

How to customize publish area in WordPress?

I want to add a text message in "publish" area in admin panel.
Are there any filters or actions to edit?
http://codex.wordpress.org/Plugin_API/Action_Reference
such as
add_atction('in_admin_footer', 'blahblah');
function blahblah($content) {
$content .= '<strong> Please make sure you input correct data</strong>';
return $content;
}
The 'in_admin_footer' action helps to add a message to the real footer of admin panel.
I want to Publish area.
http://gyazo.com/8342ffb94ae1a829988257bf2506c3d6
(string(0) "" is addded by in_admin_footer action)
Try the post_submitbox_misc_actions action hook. Something along these lines:
function submitbox_callback() {
global $post;
if ($post->post_type == 'post') { //if you only want to display this on posts
echo '<strong> Please make sure you input correct data</strong>';
}
}
add_action( 'post_submitbox_misc_actions', 'submitbox_callback' );

Redirect from add_menu_page

I have added a menu using add_menu_page which all works correctly, but when clicked I want this menu page to open the post editor for a particular post id.
As a proof of concept i have tried echoing a javascript redirect out into the do function like so...
// Load up the menu page
function register_availability_custom_menu_page() {
add_menu_page('custom menu title', 'Availability', 'add_users', 'options', 'options_do_page');
}
function options_do_page() {
echo "<script type=\"text/javascript\">";
echo "window.location = '/whatever_page.php';";
echo "</script>";
}
This approach does work but I was wondering if it is the best approach, is there a better way to redirect to the page I am after?
UPDATE
I have now also tried using wp_redirect with this code...
add_action( 'admin_menu' , 'admin_menu_new_items' );
function admin_menu_new_items() {
wp_redirect( home_url() );
exit;
}
This gives me a Headers already sent error, can anyone suggest where I am going wrong?
If I'm understanding this correctly, you don't need the redirect. Instead of using a $menu_slug in the function add_menu_page, put the address of the target page, e.g.:
$the_post_title = 'The Portfolio';
add_action( 'admin_menu', 'wpse_59050_add_menu' );
function wpse_59050_add_menu()
{
global $the_post_title;
$our_page = get_page_by_title( $the_post_title );
$settings_page = add_menu_page(
'Edit '.$our_page->post_title,
'Edit '.$our_page->post_title,
'add_users',
'/post.php?post='.$our_page->ID.'&action=edit',
'',
'',
2
);
}
This function is from the following WordPress Answer: Highlighting a Menu Item by Post Name. You'll need some jQuery to do the correct highlighting of this top level menu, check both my and TheDeadMedic answers in that Q.
This other one is useful too: Add highlighting to new Admin Dashboard Menu Item.
Recently did this for pootle page builder, and this AFAIK is the best way,
/**
* Redirecting from Page Builder > Add New page
* #since 0.1.0
*/
function add_new() {
global $pagenow;
if ( 'admin.php' == $pagenow && 'page_builder_add' == filter_input( INPUT_GET, 'page' ) ) {
header( 'Location: ' . admin_url( 'whatever-page.php' ) );
die();
}
}
add_action( 'admin_init', 'add_new' );
Replace page_builder_add with your page slug and admin_url( 'whatever-page.php' ) with url you wanna redirect to.
We always use scrutinizer-ci for best code practices and maintain code score greater than 9.5/10, so all code (Including this) is secure and optimized ;)
Lemme know how it works for ya.
Cheers
I found a 2-step solution that doesn't use JS/JQ.
Step 1:
Near the top of your script, put the following PHP to display CSS that hides your first page:
add_action('admin_head', 'hide_my_first_page');
function hide_my_first_page(){
echo '<style>
a[href="admin.php?page=admin_menu_slug"] + ul > li.wp-first-item{
display: none;
}
</style>';
}
Where admin_menu_slug is the 4th argument passed to add_menu_page();.
Step 2:
Take the function of the page you want to run and pass it as the 5th argument in add_menu_page();

Protect wordpress theme with license key validation

I'm planning to develop some professional Wordpress Themes and would like to protect it using license keys, is it possible?
If so, would any one be willing to link to some posts or articles to help me get started?
You could set up a database on your own server, holding the license key and the licensed url for the theme. Then, set up an admin page for your theme. Within, first register a license settings array. Then implement a hidden settings field on that same page that gets updated whenever the license key is being updated by site admin. the update function sends a request to your server passing the license key and the $_SERVER's host and setting the hidden license_settings field to either true or false.
A really simplified code would look like this:
functions.php
<?php
// functions.php
require("myadminpage.php");
# Functions follow here...
?>
myadminpage.php
<?php
// myadminpage.php
// register settings
function my_settings_init() {
register_setting('settings_license', 'settings_license');
}
// register admin page
function my_add_admin_page() {
add_menu_page(__( '' ), __( 'Manage License' ), 'administrator', 'myadminpage', 'my_admin_page');
}
add_action('admin_init', 'my_settings_init');
add_action('admin_menu', 'my_add_admin_page' );
if(isset($_GET["settings-updated"]) && $_GET["settings-updated"] == true) {
$options = get_option('settings_license');
$key = $options["key"];
$host = parse_url($GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'], PHP_URL_HOST);
$url = sprintf("http://you.com/check-license.php?key=%s&url=%s", $key, $host);
$options["valid"] = trim(file_get_contents($url)) == 1) ? "true" : "false";
update_option('settings_license', $options);
}
// callback function that renders your admin page
function my_admin_page() {
settings_fields('settings_license');
$options = get_option('settings_license');
?>
<form method="post" action="options.php">
<input id="settings_license[key]" type="text" name="settings_license[key]" value="<?php echo $options["key"]; ?>">
<input id="settings_license[valid]" type="hidden" name="settings_license[valid]" value="<?php echo $options["valid"]; ?>">
<input type="submit" value="Save">
</form>
<?php
}
?>
Now you can, when ever you need/want, get the license options and handle the invalid usage in any way you want. Eg (a rude way):
header.php
<?php
// very first line
$license = get_option('settings_license');
// see: http://ckon.wordpress.com/2006/08/09/server-request_uri-doesnt-always-work-correctly-heres-how-to-fix/
$ruri = $GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'];
if(!preg_match("#wp-admin#", $ruri) && $license["valid"] != "true") {
wp_die( __('This website uses unlicensed software.<br>Administrators can update their license key here.') );
}
# rest of header.php comes here..
Finally obfuscate your php code (eg http://www.ioncube.com/sa_encoder.php) and you're done. However, make sure you're not violating any other licenses, such as WP's. If there's one single line of WordPress core functions used within your final code, you can not release it under any other license than WP, which is GPL.
I don't think so. After all, the users must have the php code to use the theme and if they have it - they may alter it in a such way that it won't need a key any more.

Resources