Check for logged in users from outside wp page in wordpress - 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);
});

Related

Message when redirected by a hook on wordpress

I am using a small code snipet to redirect non logged user from the shop page to the main page.
function my_redirect() {
//if you have the page id of landing. I would tell you to use if( is_page('page id here') instead
//Don't redirect if user is logged in or user is trying to sign up or sign in
if( !is_user_logged_in() && is_page('shop')){
echo 'Non logged user - You are redirected to the main page';
exit( wp_redirect( get_permalink(2604) ) );
}
}
add_action( 'template_redirect', 'my_redirect' );
This is working fine.
However I would like to prompt a message saying "You must be log to access the shop".
I don't know how to do it, my echo in the code do not display anything.
Any idea ?
Thx
You will never see the output of the echo because this action is triggered just before wordpress decides which template to load, so it's an echo in the middle of nowhere (and why the wp_redirect is inside and exit function?)

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/

Virtual pages in wordpress with post data

I look for a function with allow me to have a virtual page which call a template page with POST data.
For exemple, when I write :
www.mysite.com/virtual-page
call
www.mysite.com/reel-page
with a post data
I would like user only see www.mysite.com/virtual-page in url bar.
Has someone any idea ?
I try with the following code which give only a redirection.
function my_page_template_redirect()
{
$url = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
if ($url == 'virtual-page')
{
//echo "tet";
wp_redirect("reel-page");
exit();
}
}
add_action( 'template_redirect', 'my_page_template_redirect');

Wordpress - admin pre-output hook with permission check

On my wordpress plugin, I want to make a "export table as CSV" feature that can only be downloaded by the highest kind of admin.
What is the best hook to use and how to check for the permission?
<?php
add_action( 'admin_init', 'xxxxxx_admin_init' );
function xxxxxx_admin_init() {
# admin.php?page=xxxxxx_admin_page&&mode=export_csv
if ($_GET['page'] == 'xxxxxx_admin_page' && $_GET['mode'] == 'export_csv') {
if (!user_can('export')) {
die("Permission denied");
}
header("Content-type:text/csv");
echo "column\r\nvalue\r\nvalue";
die();
}
}
Thanks in advance
edit: added die(); after csv echo
Check for one of the admin abilities, like user_can('manage_options')
Wordpress Roles and Capabilities

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