Adding Custom Cookie To Wordpress - php

Hi I am pretty new to wordpress,php and all this editing thing. I want to add a new cookie to wordpress upon authentication with name "xxx" and value "(currentusername)". I already read http://wptheming.com/2011/04/set-a-cookie-in-wordpress/ . I add the required code to the functions.php of my code however I don't know how to invoke it such that the currentusername logginned is added to the cookie.
Thanks in advance
Here is the code on the other website which I inserted in my functions.php
function set_newuser_cookie() {
if (!isset($_COOKIE['sitename_newvisitor'])) {
setcookie('sitename_newvisitor', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);
}
}
add_action( 'init', 'set_newuser_cookie');

Bumped into this one - I recommend against adding a new cookie, instead I would hijack (take advantage of) the current cookie and let WP manage it for you. Additionally the hooks available in WP allow very clean and tight code using WP features - try the snippet below - I put in comments and tried to be verbose :
function custom_set_newuser_cookie() {
// re: http://codex.wordpress.org/Function_Reference/get_currentuserinfo
if(!isset($_COOKIE)){ // cookie should be set, make sure
return false;
}
global $current_user; // gain scope
get_currentuserinfo(); // get info on the user
if (!$current_user->user_login){ // validate
return false;
}
setcookie('sitename_newvisitor', $current_user->user_login, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false); // change as needed
}
// http://codex.wordpress.org/Plugin_API/Action_Reference/wp_login
add_action('wp_login', 'custom_set_newuser_cookie'); // will trigger on login w/creation of auth cookie
/**
To print this out
if (isset($_COOKIE['sitename_newvisitor'])) echo 'Hello '.$_COOKIE['sitename_newvisitor'].', how are you?';
*/
And yes, use functions.php for this code. Good luck.

Related

Why is if is admin not working?

I edited a bit of code the other day from the Wordpress Ultimate Members plug-in to change the user profile to pending if the profile is edited by the user.
However, I noted that the code also sets the admin account to pending too. I don’t want this, so I have been trying to use an if/ else statement to query if the user is admin before the script runs.
I know this is straight forward for experts in PHP, but I have tried lots of variations and admin is still being set to pending approval.
Here’s the original code that is setting admin to pending:
// Set profile to under review after edits
add_action('um_user_edit_profile', 'um_post_edit_pending_hook', 10, 2);
function um_post_edit_pending_hook($user_id, $args){
global $ultimatemember;
$ultimatemember->user->pending();
}
Here s the code that I am trying to bypass admin with which won’t work. I won’t add all the variations I have tried.
add_action('um_user_edit_profile', 'um_post_edit_pending_hook', 10, 2);
function um_post_edit_pending_hook($user_id, $args){
if ( is_admin() ) {
return false;
} else {
global $ultimatemember;
$ultimatemember->user->pending();
}
}
Any assistance would gratefully be appreciated.
This Conditional Tag checks if the Dashboard or the administration panel is attempting to be displayed. It should not be used as a means to verify whether the current user has permission to view the Dashboard or the administration panel (try current_user_can() instead):
https://codex.wordpress.org/Function_Reference/current_user_can
Source:
https://codex.wordpress.org/Function_Reference/is_admin
#user45250 has explained this very well. I have added this answer to provide some example code.
Here is the code from my earlier comment.
add_action('um_user_edit_profile', 'um_post_edit_pending_hook', 10, 2);
function um_post_edit_pending_hook($user_id, $args){
if ( current_user_can('administrator') ) {
return false;
} else {
global $ultimatemember;
$ultimatemember->user->pending();
}
}
P.S. here is a related question, gmazzap's answer has more detail.

Setting a cookie in WordPress plugin, cookie gets deleted automatically

I'm currently trying my hands on WordPress plugind developement for an exercise and came across some little snag.
The plugin is designed to display a simple poll in a widget on the front page. Once the visitor has voted, I use setcookie to drop a cookie containing his vote for 30 days, and some simple code to change the widget so that it shows the results and the user cannot vote again until a new poll is proposed. The problem is, voting is still possible, the results are never shown. Looking at the logs with the developer's tools, I found that the cookie is deleted the second it lands on the client browser. Does anybody know why, and how I can correct that?
Here's the code. First, the action hook:
public function __construct()
{
parent::__construct('poll_plugin', __('Polls', 'poll_plugin'), array('description' => __('Simple poll widget', 'poll_plugin')));
add_action('init', array($this, 'save_votes'));
}
Then, the actual action:
public function save_votes()
{
global $wpdb;
/*Cookie setting, 30 days expiration */
if ( isset($_POST['option']) && !isset($_COOKIE['Poll_Votes']))
{
unset($_COOKIE['Poll_Votes']);
setcookie('Poll_Votes', $choix, 30 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);
$choix = $_POST['option'];
$id_choix = $wpdb->get_var("SELECT id FROM {$wpdb->prefix}poll_options WHERE label = '$choix'");
$wpdb->query("UPDATE {$wpdb->prefix}poll_results SET total = total+1 WHERE option_id = '$id_choix'");
};
/*Testing the presence of a new poll */
$vote = $_COOKIE['Poll_Votes'];
/*If the cookie's value isn't found in the db, the poll's changed, so we reset the cookie*/
if (is_null($wpdb->get_var("SELECT * FROM {$wpdb->prefix}poll_options WHERE label = '$vote'")))
{
setcookie('Poll_Votes', '', time()-3600);
}
}
Quick note here, I already tried commenting the line designed to unset the cookie, it changed nothing.
The only other time where the cookie is mentioned is via the $_COOKIE global, in a isset().
And lastly, please forgive my english, I'm french :)

How to perform custom action when WordPress comment is posted?

I am trying to set a custom cookie when a visitor submits a comment, but I can not seem to get this working. Here's what I have in functions.php:
add_action('comment_post', 'ipro_set_comment_cookie');
function ipro_set_comment_cookie($comment) {
setcookie("visitor_name", $comment->comment_author, time()+86400);
setcookie("visitor_email", $comment->comment_author_email, time()+86400);
}
I've also tried changing comment_post to wp_insert_comment- neither have seemed to work. I am working off of WP's action references:
http://codex.wordpress.org/Plugin_API/Action_Reference#Comment.2C_Ping.2C_and_Trackback_Actions
...any ideas?
Check out the Database writes in the Filter Reference
Try something like comment_save_pre
applied to the comment data just prior to updating/editing comment data. Function arguments: comment data array, with indices "comment_post_ID", "comment_author", "comment_author_email", "comment_author_url", "comment_content", "comment_type", and "user_ID".
That way it sets on submit (so it calls after your error handling kicks in)
If I understand your question correctly, this should work:
add_action('comment_save_pre', 'ipro_set_comment_cookie');
function ipro_set_comment_cookie($comment) {
setcookie("visitor_name", $comment->comment_author, time()+86400);
setcookie("visitor_email", $comment->comment_author_email, time()+86400);
}

Passing a php variable into a gravity forms hook

I think I'm getting really confused with return'ing and echo'ing variables.
I've got this gravity forms hook from their support...
add_filter('gform_field_value_facebook_name', 'my_custom_population_function');
function my_custom_population_function($value){
return 'boom!';
}
This works and returns 'boom!' as my form field default variable.
This is pretty straight forward for a general text string, but I am trying to return a PHP variable instead.
I am loading the facebook PHP SDK in my functions.php at a higher scope than the gravity form hook. The facebook SDK definitely works, for example I am currently echoing this in my wordpress theme files...
echo $userData['name']
But my question is, why does it not work if I try and return the above variable inside the gravity for hook?
Please see what I have tried below, but it returns nothing...
add_filter('gform_field_value_facebook_name', 'my_custom_population_function');
function my_custom_population_function($value){
return $userData['name'];
}
I've also tried something similar in my wordpress functions.php, when trying to echo a variable in a filter...
$fb_app_id = '12345678910';
// APP ID FILTER
add_action( 'fb_app_id', 'echo_fb_app_id' );
function echo_fb_app_id() {
echo $fb_app_id;
}
But this returns nothing and the scope is the same.
Can anyone please enlighten me to why I can't pass these variables around. I think thats the technical term. Thank you very much.
This is because in PHP, functions don't read global variables without the global keyword.
$fb_app_id = '12345678910';
// APP ID FILTER
add_action( 'fb_app_id', 'echo_fb_app_id' );
function echo_fb_app_id() {
global $fb_app_id; // tells PHP to use the global variable
echo $fb_app_id;
}
Try to add global $userData; to your my_custom_population_function.

Wordpress plugin: Hook on custom url

I want to make a plugin, that I will use for some jQuery AJAX loading of table data.
I have a function that prints the data correctly, but how do I "hook" into a specific url?
Like say, I want the function to be run, and the data to be printed whenever a request to /mycustomplugin/myurl.php is run? (Please note that the url/file should not exist)
I have no experience with WP plugins.
To filter your custom URL before Wordpress starts executing queries for other things use something like this:
add_action('parse_request', 'my_custom_url_handler');
function my_custom_url_handler() {
if($_SERVER["REQUEST_URI"] == '/custom_url') {
echo "<h1>TEST</h1>";
exit();
}
}
A simple
if ($_SERVER["REQUEST_URI"] == '/mycustomplugin/myurl.php') {
echo "<my ajax code>";
}
Should work wonders.
If you wanted to return regular wordpress data you could just include wp-blogheader.php into your custom php file like so
//Include Wordpress
define('WP_USE_THEMES', false);
require('Your_Word_Press_Directory/wp-blog-header.php');
query_posts('showposts=10&cat=2');
Just use regular theming tags to return the content you desire. This
Where is your table data coming from though? Are you trying to show this information on the admin side or the viewer side?
Also see for a full breakdown of calling hooked functions with wp_ajax http://codex.wordpress.org/AJAX_in_Plugins
add_action( 'init', 'my_url_handler' );
function my_url_handler() {
if( isset( $_GET['unique_hidden_field'] ) ) {
// process data here
}
}
using add_action( 'init', 'your_handler') is the most common way in plugins since this action is fired after WordPress has finished loading, but before any headers are sent. Most of WP is loaded at this stage, and the user is authenticated.

Categories