Update meta_value in wp_postmeta from an API response - wordpress

I'm making an API call using the wp_remote_get method to fetch data from an external source (not a WP site). The API call is working and i'm getting back the response i want which is just a number. Now i want to store this number (the response) as a meta_value in wp_postmeta with the following meta_key (donation_amount) and a specific post_id. The database table already exists. What i have so far is the API Call and the response. I've tried wp_update_post but maybe i am doing something wrong or maybe is not the right approach. Any help would be appreciated.
$url = 'https://developer.mozilla.org/en-US/docs/Web/API/URL_API'; // Not the real url
$response = wp_remote_get( $url );
if( is_wp_error( $response ) ) {
return false;
} else {
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
}
echo $api_response ['theNumber'];

Use WP update_post_meta function. check the below code.
$url = 'https://developer.mozilla.org/en-US/docs/Web/API/URL_API'; // Not the real url
$response = wp_remote_get( $url );
if( is_wp_error( $response ) ) {
return false;
} else {
$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
}
$donation_amount = $api_response['theNumber'];
replace $post_id with your post id.
update_post_meta( $post_id, 'donation_amount', $donation_amount );

Related

Create a Cron job after every post publish

I have a situation where i want to create a cron job after every WordPress blog post publish. Cron job will run after 7 days of publishing post and check if all the users have viewed the posts and email the list of not viewed post by users list. How can i achieve this. Its a WordPress website and there are around 300+ users, after each blog post publish user gets notification. So want to check who has viewed and who has not viewed the post.
If you want to start the cron job only the first time a post is published, you'll want to use the draft_to_publish hook.
draft_to_publish
Well there are Plugins capable of managing Stats and tracking users activities. I'm not sure which one fit to your needs but I'll try to give a simple approach to do it by yourself.
Tracking
We can set a custom field for those (posts/post-types) where we will store a list of users who read that post. Let's call it readerslist
On the single.php file we will add these lines to Update this field.
$list = explode(',',get_post_meta($post->ID, 'readerslist', true));
$user = get_current_user_id();
if (!in_array($user,$list)){
array_push($list, $user);
update_post_meta( $post->ID, 'readerslist', implode(",", $list) );
}
Now that we can retrieve who viewed the article? We could later find those who didn't read it yet.
Then in functions.php we could set up a hook that will execute when a post get published, to set a single scheduled cron job to send the absent readers.
<?php
function wpdocs_run_on_publish_only( $new_status, $old_status, $post ) {
{
if ($new_status != 'publish') {
return;
}
//You better add limitations to choose specific post_types you are targeting
$postid=$post->ID;
add_cron($postid);
}
add_action( 'transition_post_status', 'wpdocs_run_on_publish_only', 10, 3 );
function add_cron($postid){
$nxtweek = strtotime("+1 week");
add_action('sendemail', 'stats_mail', 10, 1);
wp_schedule_single_event(time() + $nxtweek, 'sendemail',array( $postid);
}
function stats_mail($postid)
{
$readerslist = get_post_meta( $postid, 'readerslist', true );
$users = get_users( array( 'fields' => array( 'ID' ) ) );
$absents = array_diff($users, explode(",",$readerslist));
//Now that you got the list of absent users
$names='';
foreach ($absents as $x){
$names.=$x.' : '.get_user_meta( $x,'first_name' , true ).' '.get_user_meta( $x,'last_name' , true ).'<br>';
}
$title=get_the_title($postid);
$to = 'you#example.com';
$subject = 'Users who didn\'t read '.$title;
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $names, $headers );
}
?>
Notice : I didn't tested the above code ! I made you this in order to show you how to do it. But there isn't much work to do here. Good luck
I tried your code, it works fine, but i am not able to make it working as i wanted, can you look into it. I don't know what i am doing wrong.
function wpdocs_run_on_publish_only( $new_status, $old_status, $post ) {
if ($new_status != 'publish') {
return;
}
$postid=$post->ID;
add_cron($postid);
}
add_action( 'transition_post_status', 'wpdocs_run_on_publish_only', 10, 3 );
function add_cron($postid){
$nxtweek = strtotime("+1 week");
add_action('sendemail', 'stats_mail', 10, 1);
if ( ! wp_next_scheduled( 'sendemail') ) {
wp_schedule_event(time() + $nxtweek, $nxtweek, 'sendemail', array($postid));
// i want to run cron every 7 days from the date of publishing post, until all user reads it, i tried this code but not working.
// wp_mail( 'email#company.com', $postid, 'test', null );
// For testing purpose if i send mail from here, it goes.
}
}
function stats_mail($postid) {
wp_mail( 'email#company.com', $postid, 'test', null );
// this doesnt work.
$readerslist = get_post_meta( $postid, 'readerslist', true );
$users = get_users( array( 'fields' => array( 'ID' ) ) );
$absents = array_diff($users, explode(",",$readerslist));
//Now that you got the list of absent users
$names='';
foreach ($absents as $x){
$names.=$x.' : '.get_user_meta( $x,'first_name' , true ).' '.get_user_meta( $x,'last_name' , true ).'<br>';
}
$title=get_the_title($postid);
$to = 'email#company.com';
$subject = 'Users who didn\'t read '.$title;
$headers = array('Content-Type: text/html; charset=UTF-8');
//wp_mail( $to, $subject, $names, $headers );
}

Send email notification when new post from post type is created

I'm having a time trying to get this to work and I feel like I have tried everything from transition_post_status, to wp_insert_post and even draft_to_pending for my actions.
I'm trying to send an email to a user and the post author. The user is set via ACF user object. The problem I think, is that possibly the meta is not available or something because $author and $user are not objects so it's not finding them by the ID and grabbing their data.
Here is my function:
add_action( 'transition_post_status', 'send_volunteer_request_email', 10, 3 );
function send_volunteer_request_email( $new_status, $old_status, $post ){
if ( 'volunteers' !== get_post_type( $post ) )
return;
if( wp_is_post_autosave( $post ) ) return;
$user = get_field('user', $post);
$user_data = get_userdata( $user );
$the_event = get_field('event', $post);
$event = get_post($the_event);
$eventLink = get_permalink($event);
$author = get_userdata( $event->post_author );
if(get_post_status($post) == 'pending'){
//Notify event author
$headers = array('Content-Type: text/html; charset=UTF-8');
$subject = 'You have a new volunteer';
$body = '<p>A member has volunteered to meet your need. Click here to view and accept or decline!</p>';
$body .= '<p>Thank you for being a valuable member<br>https://www.goole.com<br>910-555-1234</p>';
wp_mail( $author->user_email, $subject, $body, $headers );
}
}
Here is an example of one of the errors:
PHP Notice: Trying to get property 'user_email' of non-object
And finally, you can see where these are set
Try changing your code as below:
$user = get_field('user', $post->ID);
$user_data = get_userdata( $user );
$the_event = get_field('event', $post->ID);
$event = get_post($the_event);
The reason that you are getting the error is because you were passing post object to get_field function instead of post id.

Can I turn a WordPress Draft into a published post with a direct link if I know the post ID?

For example, using a function like this:
http://website.com/wp-admin/post.php?post=%%post_id%%&action=publish
P.S. I checked and this does not work, but I'm wondering if there is something similar in spirit that works?
You can paste this code in your theme functions.php file. This will do the trick, now if you change action parameter to draft and sent a get request , it will make that post draft.
add_action( 'admin_init', 'draft_post_status_221' );
function draft_post_status_221(){
// Get current page , so this action will only fire in post.php page.
global $pagenow;
if ( $pagenow != 'post.php' ){
return;
}
$post_id = false;
$action = false;
// get post id
if ( isset($_GET['post']) && !empty($_GET['post']) ){
$post_id = $_GET['post'];
}
// get action
if ( isset($_GET['action']) && !empty($_GET['action']) ){
$action = $_GET['action'];
// for security we only allow draft action
if ( $action != 'draft' ){
$action = false;
}
}
// if $post_id and $action has data than post will be updated.
if ( !empty($post_id) && !empty($action) ){
$args = array(
'ID' => $post_id,
'post_status' => $action
);
wp_update_post( $args );
}
}

after setup theme action creating issue with nonce in wordpress 4.3.1

I am using add_action( 'after_setup_theme', 'custom_login' ); hook in one of my website for auto redirect user to his dashboard page.
Here is my code :---
function custom_login($username, $password='') {
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ){
echo $user->get_error_message();
}
}
// run it before the headers and cookies are sent
add_action( 'after_setup_theme', 'custom_login' );
Its working fine on old version, But now I have upgrade wordpress version and its creating problem with nonce.
Are you sure you want to do this?
Everytime this error display on the screen when I do anything like update plugin, theme and permalinks.
When I comment this code then website working fine except auto redirect functionality.
Here is my website url :- https://www.linearrecruitment.co.uk/
Please help me where I do mistake.
That's a normal behaviour - nonce is a token used by Wordpress to check the validity of the form in order to prevent CSRF attacks.
A valid login form in Wordpress should have an hidden input field generated with wp_nonce_field:
wp_nonce_field('my_login_form');
Then in the login function the token is checked with the wp_verify_nonce function:
if (!isset($_POST['my_login_form']) || !wp_verify_nonce($_POST['_wpnonce'], 'my_login_form')) {
die('Invalid form');
}
What you're trying to do (auto login) is done wrong as add_action doesn't send any parameter for the after_setup_theme hook, so your username is probably empty. I don't know how this could possibly work before, maybe it managed to log in somehow with an empty username.
I suggest you to declare some globals vars for your username and password, as it seems to be static inputs:
global $username, $password;
$username = 'my_login';
$password = 'my_password';
And then on the beginning of your function import those globals with:
global $username, $password;
So what about the nonce?
On the last versions of Wordpress, the check_admin_referer have changed a bit, from:
function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
if ( -1 == $action )
_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
$adminurl = strtolower(admin_url());
$referer = strtolower(wp_get_referer());
$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) {
wp_nonce_ays($action);
die();
}
do_action( 'check_admin_referer', $action, $result );
return $result;
}
To :
function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
if ( -1 == $action )
_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
$adminurl = strtolower(admin_url());
$referer = strtolower(wp_get_referer());
$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
do_action( 'check_admin_referer', $action, $result );
if ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {
wp_nonce_ays( $action );
die();
}
return $result;
}
As you can see they moved the check_admin_referer hook - now we can change the value of $result before the wp_nonce_ays function (the one that display the message you try to get rid of) as been called.
That mean we could add the following hook in the theme functions.php in order to force the nonce validation:
add_action( 'check_admin_referer', array('custom_check_admin_referer' ) );
function custom_check_admin_referer() {
return 1;
}
That should work around your problem, but you must be aware that this could possibly be a security issue - you maybe want to do more test in that function before returning 1.

Change user profile URL in Buddypress with nickname or userID

I am using this code which is partially working for changing the profile url everywhere in buddypress and wordpress from “http:/mywebsite/user/username” to “http:/mywebsite/user/userid”
function _bp_core_get_user_domain($domain, $user_id, $user_nicename = false, $user_login = false) {
if ( empty( $user_id ) ){
return;
}
if( isset($user_nicename) ){
$user_nicename = bp_core_get_username($user_id);
}
$after_domain = bp_get_members_root_slug() . '/' . $user_id;
$domain = trailingslashit( bp_get_root_domain() . '/' . $after_domain );
$domain = apply_filters( 'bp_core_get_user_domain_pre_cache', $domain, $user_id, $user_nicename, $user_login );
if ( !empty( $domain ) ) {
wp_cache_set( 'bp_user_domain_' . $user_id, $domain, 'bp' );
}
return $domain;
}
add_filter('bp_core_get_user_domain', '_bp_core_get_user_domain', 10, 4);
function _bp_core_get_userid($userid, $username){
if(is_numeric($username)){
$aux = get_userdata( $username );
if( get_userdata( $username ) )
$userid = $username;
}
return $userid;
}
add_filter('bp_core_get_userid', '_bp_core_get_userid', 10, 2);
function _bp_get_activity_parent_content($content){
global $bp;
$user = get_user_by('slug', $bp->displayed_user->fullname); // 'slug' - user_nicename
return preg_replace('/href=\"(.*?)\"/is', 'href="'.bp_core_get_user_domain($user->ID, $bp->displayed_user->fullname).'"', $content);
}
add_filter( 'bp_get_activity_parent_content','_bp_get_activity_parent_content', 10, 1 );
add_filter('bp_core_get_userid_from_nicename', '_bp_core_get_userid', 10, 2);
It is working perfectly for me at the moment BUT not on this little place (see picture):
http://i.imgur.com/4dX0RUB.png
– url change of the author of an activity starting-message is not working in both groups activities and personnal activities
url change of the author of an activity REPLY is working
I don’t know if I am explaining very well what issue I have got but I hope you will understand.
Thank you for your answers
PS : thanks to aSeptik from StackExchange for the code
It's impossible to do that on a fly gracefully. BuddyPress Activity component is developed in such a way, that those text with the user link in activity stream (for site-wide, personal and groups) is stored directly in the database as an action. Just take a look at wp_bp_activity.action field in your DB.
So you should filter and preg_replace it as well. I guess you know that you are penalting yourself with rendering speed loss.

Resources