I want to write PHP script (standalone) for comment approval.
Objective:
I use Aksimet for comment filtering. After Akismet's filtering, few comments get passed and come to my email for approval. I will get comment ID from there and pass it to the script in get parameter (manually).
This way I do not need to login to WP every time. The script will just approve comment so there is not much risk or harm. If script works then It will take less time and I can approve comment any time even from office.
I tried setting the moderation bit in MySQL directly to see if it works or not! The answer is yes and no. It approves the comment but it does not refresh the post. So, my cache show post without new comment. I use Super cache plugin.
The challenge is to write script OUTSIDE of WP environment. So, that I can access the script without Admin login.
Please suggest trick for this and how to start for this.
I spent a little time and got this working. The key is that you can use the WP API in your script by including wp-load.php.
I have tested this below and it works in my Wordpress. It uses GET parameters 'commentid' and 'status'. I leave it to you to extend, test for error conditions, provide appropriate security mechanisms, etc.
<?php
include('wp-load.php');
echo 'Running comment approval...<br>';
$wp_error = false;
if(isset($_GET['commentid']) && isset($_GET['status']) )
{
$comment_id = $_GET['commentid'];
$comment_status_to_set = $_GET['status'];
$current_status = wp_get_comment_status( $comment_id );
echo 'Current comment status is ' . $current_status .'<br>';
echo 'Setting status to ' . $comment_status_to_set . '<br>';
$res = wp_set_comment_status($comment_id, $comment_status_to_set, $wp_error);
$new_current_status = wp_get_comment_status( $comment_id );
echo 'Now status is ' . $new_current_status . '<br>';
}
else
{
echo 'No comment parameters passed in url';
}
?>
And here is the usage for wp_set_comment_status, from the source code:
#param int $comment_id Comment ID.
#param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
#param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
#return bool False on failure or deletion and true on success.
Also, so those who are curious know how I went about solving this... basically I checked the /wp-includes/ directory of WP to see if there were any comment related files. There is a file called comment.php in there, which has most, if not all, of the main comment manipulation functions that the wordpress API uses.
#param int $comment_id Comment ID.
#param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
#param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
#return bool False on failure or deletion and true on success.
Related
i want to set a cookie if a specified form (Contact Form 7) was sent.
If is write the code into the init-call it works:
function process_post() {
if( isset( $_POST['kampagne'] ) ) {
setcookie('cid', get_option( 'cf7-counter', 0) + 1 , time()+3600, '/');
}
}
add_action( 'init', 'process_post' );
But that's not good, because the value of cookie is an id - stored in database, which i must get in the moment where the form will send.
So I want to set the cookie in the "wpcf7_before_send_mail" hook. But within that the cookie will not generate.
function wpcf7_do_something($WPCF7_ContactForm)
{
$submission = WPCF7_Submission :: get_instance();
if ( $submission ){
$posted_data = $submission->get_posted_data();
if ( empty( $posted_data ) ){ return; }
$changed_name = get_option( 'cf7-counter', 0) + 1;
update_option('cf7-counter', $changed_name);
$mail = $WPCF7_ContactForm->prop( 'mail' );
$new_mail = str_replace( '[cf7-counter]', '00'. $changed_name .'', $mail );
$WPCF7_ContactForm->set_properties( array( 'mail' => $new_mail ) );
return $WPCF7_ContactForm;
}
}
add_action("wpcf7_before_send_mail", "wpcf7_do_something");
I hope you can help me.
Thank you very much!
Best regards.
But that's not good, because the value of cookie is an id - stored in database, which i must get in the moment where the form will send.
So what you need is the ID that will be stored into the database when creating the cookie.
Create it
if( isset( $_POST['kampagne'] ) ) {
$cookie = 'cid';
$id = uniqid("cid:", true);
setcookie($cookie, $id, $_SERVER['REQUEST_TIME'] + HOUR_IN_SECONDS, '/', ini_get('session.cookie_domain'), (bool)ini_get('session.cookie_secure'), (bool)ini_get('session.cookie_httponly'));
$_COOKIE[$cookie] = $id;
}
; and store it
$cookie = 'cid';
$WPCF7_ContactForm->set_properties(
[
'mail' => $new_mail,
'cid' => $_COOKIE[$cookie],
]
);
.
The contact form transaction now has the id that is in the cookie.
It is independent to get_option( 'cf7-counter', 0) by binding the submission to its own identifier - like the cookie is not the cf7-counter option.
Take note on explicitly setting $_COOKIE[$cookie] = $id;, always. This is to have the ID in the request itself.
Take double note on this action, as the code does set the cookie with a new ID even if it was already set. If that is not your intention, check if the cookie is unset beforehand (later references on setting a cookie in Wordpress have it, too).
It is now more eventually consistent, up to the level of uniqueness of the uniquid() function (study it if you want to make use of it), which is an improvement over the situation where the chance of being inconsistent was much higher (that is when using the cf7-counter option).
An insecure random-unique ID normally is enough for short term transaction tagging, e.g. having it for an hour in the cookie.
Which is something you may want to put more of your attention to. And the example is less Wordpress specific, there is more to get from in Wordpress like nonces, keys, salts, cookie-paths, user-level cookies etc. pp. to adhere to that system specifically.
It requires you to study Wordpress first, which I can't take of your shoulders, and there is even more to learn first, like how cookies work. Perhaps ask the more general questions first that you have to close such gaps.
Another answer I was thinking about first is to take a more fitting action so that you have the id the moment you can do both: setting the cookie and storing to the database.
As it has been commented, such a solution would need to find the right place in time. But that is merely how cookies work.
(And not specifically Wordpress.)
As you have already seen yourself, the action you wanted to use did not work.
And even if you would find such another action, this is still Wordpress, and it would be unpredictable that it would suffice: The cookie might be set in your tests, but not when a user visits the site (or any site that is out there with Contact Form 7 which this answer should answer if it is worth it).
To set a cookie in Wordpress, there is no free choice of the action to do it in, but it first of all needs to set the cookie for which the action is invariant:
How to set a cookie in Wordpress
Setting a redirect cookie in wordpress
As the action is set in stone to set a cookie, this goes back to the answer above.
However this is not Wordpress SE, but Stackoverflow so I've put the focus more on the PHP code itself where it relates to the PHP configuration and only HOUR_IN_SECONDS is a constant from Wordpress in it. See as well my comment on it about more specific Wordpress features you may want to add to it.
It hopefully answers your question to the level you need it.
I need to get the current user id to lookup customer information, in order to pass it to an api call to process a payment.
I have tried:
$user = wp_get_current_user();
echo ( isset( $user->ID ) ? (int) $user->ID : 0 );
and:
$userid = get_current_user_id();
echo $userid;
But when I run the php file, the process stops at the first line and does not display anything after it. I dont get an error or nothing, just a blank screen.
I have been searching for solution for 2 weeks. All results says that these codes should work, but does not for me.
I have also added the require('to user.php') and doe not work.
I even enter this php code into Dreamweaver, and "wp_get_current_user" or "get_current_user_id" does not turn blue like other function calls do, but get_current_user() does turn blue, but this is the websites owners user not the current user.
Please help if you can, much appreciated.
Thanks
Here is my code:
<?php
echo "here";
/**
* Lookup the customer information.
*
* #since 1.0.0
*
* #return void
*/
echo "is";
function lookup_customer_information() {
$current_user = wp_get_current_user();
if ( ! is_object( $current_user ) || ! isset( $current_user->ID ) ) {
echo $current_user;
return;
}
echo "the";
echo "code";
// do your business logic here.
}
?>
<?php $userinfo = lookup_customer_information();
echo $userinfo;
?>
From what you describe, it sounds like WordPress Core has not loaded the wp-includes/user.php file yet or the current user has not been setup yet.
WordPress, like all apps, load in a particular order. What may be causing the issue for you is the current user has not been setup and/or the user files (in Core) have not loaded yet.
Let's See if Function is Available
Let's discover if the function wp_get_current_user is ready to be used. You can do any of these:
Check the PHP error logs
Check your settings to display the errors
Put code in to check for it
Let's use the third option to show you if it's available or not. Put this code snippet in above your if conditional you show in your question:
if ( ! function_exists( 'wp_get_current_user' ) ) {
die('The file with wp_get_current_user() has not loaded yet into memory.');
}
The code will use the PHP construct function_exists to check if wp_get_current_user has been loaded into memory. If yes, you will not get the message, as it's ready. Else, the website will stop loading and you'll get the above message displayed on the screen.
No, It's Not Available
If the website renders the above message on the screen, then you know it's not loaded into memory yet. That means you are trying to use it before WordPress Core has loaded it.
How to Fix
Delay. You want to wait until WordPress has setup the user. Typically, you can register to the init event or later. For example, you can do this:
add_action( 'init', 'lookup_customer_information' );
/**
* Lookup the customer information.
*
* #since 1.0.0
*
* #return void
*/
function lookup_customer_information() {
$current_user = wp_get_current_user();
if ( ! is_object( $current_user ) || ! isset( $current_user->ID ) ) {
// you might want to post a message
return;
}
// do your business logic here.
}
Yes, It Is Available
When running the function_exists() snippet above, you did not get the message. Hum, something else is up then.
Now, it's time to dig into your PHP error logs to see what is going on. You can post them to help us help you.
when i open my web site in homepage i see only header and this error :
Catchable fatal error: Object of class WP_Error could not be converted
to string in /home/mahooorc/public_html/wp-includes/formatting.php on
line 3275
this problem is just on my homepage and other links are ok. i disabled all plugins but it doesn't answer! line 3275 is
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%#$\|*\'()\\x80-\\xff]|i', '', $url);
function esc_url( $url, $protocols = null, $_context = 'display' ) {
$original_url = $url;
if ( '' == $url )
return $url;
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%#$\|*\'()\\x80-\\xff]|i', '', $url);
This is usually caused by missing taxonomies that are used in a menu, but do not exist anymore.
You have a couple of solutions to try, but do not forget to always create a backup of your files and database before you try any of them.
Method 1
Remove the taxonomy items from the menu
Delete all session data, cookies etc...
Method 2
Find the table wp_term_taxonomy in the database
Find a record called nav_menu
Delete that record
Method 3
Find the table wp_terms in the database
Look at the different terms and decide which ones you do not need
Delete the terms you do not need anymore
When none of these solutions, or a combination of the solutions work, please let me know. You have still a couple more options, but those are a lot more destructive.
Instead of receiving the expected $url as as string, the esc_url() function receive a WP_Error object.
Try to add this code before the faulty line to learn more about the error:
echo $url->get_error_message();
It will display the error message which can help you understand where it comes from.
Remember to remove this added line after that.
People having the same issue are often talking about encoding problems. Are you using special encoding ?
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 :)
I'm just starting to explore the functionalities of Google Glass.
What I'm trying to do is a simple Glassware that receives a video from the user, when the default 'Share' function is used.
I have seen the Quickstart project guide and I managed to upload my video in the python demo project; I also managed to implement the example PHP project code in my server.
However, I still can't figure out what exactly is happening where i tap the "Share" button on my Glass: where is sent the data? To my Glassware, to the generic Mirror API, or somewhere else? I suppose the Share function is doing something similar to what is described in the media upload page, but it's not clear how.
The code of the demo project seems to update the timeline event when I upload a picture/video; but if I'm not wrong, this code is just updating an already existing item with the "I have received your data!" caption.
(I'll report here the relevant code from the Google's notify.php sample: )
switch ($request['collection']) {
case 'timeline':
// Verify that it's a share
foreach ($request['userActions'] as $i => $user_action) {
if ($user_action['type'] == 'SHARE') {
$timeline_item_id = $request['itemId'];
$timeline_item = $mirror_service->timeline->get($timeline_item_id);
// Patch the item. Notice that since we retrieved the entire item above
// in order to access the caption, we could have just changed the text
// in place and used the update method, but we wanted to illustrate the
// patch method here.
$patch = new Google_TimelineItem();
$patch->setText("PHP Quick Start got your photo! " .
$timeline_item->getText());
$mirror_service->timeline->patch($timeline_item_id, $patch);
break;
}
}
...
Where and when is actually received the video? I need to know this in order to perform additional operations when I receive the data.
The shared picture or video is downloaded through the download_attachment function in mirror-client.php of the Quickstart PHP project.
Here is the function:
/**
* Download an attachment's content.
*
* #param string item_id ID of the timeline item the attachment belongs to.
* #param Google_Attachment $attachment Attachment's metadata.
* #return string The attachment's content if successful, null otherwise.
*/
function download_attachment($item_id, $attachment) {
$request = new Google_HttpRequest($attachment->getContentUrl(), 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
}