how to delete all users and posts based on 'user_meta'? - wordpress

I have developed a small wordpress application where It has Institutes(wp user), Trainers(wp user), Trainees(wp user), courses(custom post) and notifications(custom post). All the application is working fine but If I delete an institute all the information belongs to that institute like Trainers, Trainee, notifications & courses should also be deleted. While I was creating the 'institute' user I am storing the all the related info like first name, last name in wordpress table 'wp_users' and 'institute name' is storing as 'user meta' with key 'inistitute_name' in 'wp_usermeta' table like below is my code:
$user_data = array(
'ID' => '',
'user_pass' => '',
'user_login' => $first_name,
'user_email' => $user_email,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'admin'//get_option('default_option')
);
$random_password = wp_generate_password(8,false);
$user_id = wp_insert_user( $user_data );
update_user_meta( $user_id, 'inistitute_name',$insititute_name );
While creating Trainer (or) Trainee my code is like below:
$user_data = array(
'ID' => '',
'user_pass' => '',
'user_login' => $first_name,
'user_email' => $trainer_email,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'trainer'
);
$random_password = wp_generate_password(8,false);
$user_id = wp_insert_user( $user_data );
update_user_meta( $user_id, 'inistitute_name',$this->institute_name[0] );
wp_set_password($random_password, $user_id);
While creating courses my code is like below:
$user_ID = get_current_user_id();
$institute_name = get_user_meta($user_ID, 'inistitute_name', true);
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => "courses"
);
$id = wp_insert_post($post);
update_post_meta( $id, 'inistitute_name', $institute_name );
Suppose let us say if a institute 'abcd' is deleted then all the information like 'trainer', 'trainee', 'courses' & 'notifications' associated with that institute should also be deleted based on a 'user_meta' field. Is it possible to delete? (or) did I do any mistake? can anyone tell me what was I doing wrong?

Try this code:
$user_args = array(
'meta_key' => 'inistitute_name',
'meta_value' => 'your_value', //<-- replace it by your user_meta value.
'meta_compare' => '=',
'orderby' => 'ID',
'number' => -1
);
// Custom query.
$user_query = new WP_User_Query($user_args);
// Get query results.
$users = $user_query->get_results();
//print_r($users);
// Check for users
if (!empty($users))
{
// Loop over users.
foreach ($users as $user)
{
$user_id = $user->ID;
// Get each user's data.
$user_info = get_userdata($user->ID);
$user_display_name = $user_info->display_name;
$args = array(
'numberposts' => -1,
'post_type' => 'any', //<-- you can Specific type by array('post', 'my_custom_post')
'author' => $user_id
);
// get all posts by this user: posts, pages, attachments, etc..
$user_posts = get_posts($args);
if (!empty($user_posts))
{
// delete all the user posts
foreach ($user_posts as $user_post)
{
wp_delete_post($user_post->ID, true);
}
}
wp_delete_user( $user_id, $reassign );
}
}
else
{
//"no user found"
}
I haven't tested this code, out form my WP knowledge.
Please note before testing this code do take a Database backup.

I got the solution form wordpress.stackexchange.com link to that question is here
https://wordpress.stackexchange.com/questions/249435/how-to-delete-all-users-and-posts-based-on-user-meta/

Related

uploading image from ACF image thru phone not working

here's my code to submit post from frontend using ACF, all of this are working fine in desktop but when I tried to post using phone the image appears in media library but not in CPT, does anyone here have any idea? thanks
$user_info = get_userdata(get_current_user_id());
$args = array(
'post_id' => 'new_post',
'field_groups' => array(570), //it's the ID of your custom field Form
'form' => false,
'new_post' => array(
'post_type' => 'team_member',
'post_status' => 'pending',
'post_title' => $user_info->user_login),
);
acf_form( $args );
Function.php
function my_pre_save_post( $post_id ) {
// bail early if not a new post
if( $post_id !== 'new_post' ) {
return $post_id;
}
$my_post = array(
'post_type' => 'team_member'
);
// insert the post
$post_id = wp_insert_post( $my_post );
}

$order->get_checkout_payment_url() different behavior for product and subscription

I'm trying to create subscription order by code. I'm using the latest version of Woocommerce and Woocommerce Subscription plugins. It's working fine, but I got different order-pay page when the order contains subscription product.
When the order contains a subscription, I got all the billing and the shipping fields. If the order only contains simple products, I got a summary about the order and the payment methods. I would like the same behavior for subscriptions.
Example link:
https://test.eu/hu/cart/order-pay/4467/?pay_for_order=true&key=wc_order_161651fdsf56
I generate the link with the method get_checkout_payment_url and I got similar link in both cases, but if the order contains a subscription, I 'm redirected to the cart page immediately.
Does anybody faced with same problem?
Thank you for any help!
Best regards,
Mark
$start_date = $order_data['created_at'];
$billing_address = array(
'first_name' => $order_data['first_name'],
'last_name' => $order_data['last_name'],
'company' => $order_data['company_name'],
'email' => $order_data['email'],
'phone' => $order_data['phone_number'],
'address_1' => $order_data['street_address'],
'address_2' => $order_data['apartment_suite_unit'],
'city' => $order_data['town'],
'postcode' => $order_data['zip_code'],
'country' => $order_data['country']
);
$shipping_address = array(
'first_name' => $order_data['shipping_first_name'],
'last_name' => $order_data['shipping_last_name'],
'company' => $order_data['shipping_company_name'],
'address_1' => $order_data['shipping_street_address'],
'address_2' => $order_data['shipping_apartment_suite_unit'],
'city' => $order_data['shipping_town'],
'postcode' => $order_data['shipping_zip_code'],
'country' => $order_data['shipping_country']
);
$email = $order_data['email'];
if (!$user = get_user_by('email', $email)) $user = get_user_by('id', wc_create_new_customer($email));
$order = wc_create_order(array('customer_id' => $user->ID));
update_post_meta($order->ID, "phone_order", true);
foreach ($order_data['ordered_items'] as $item) {
$product = wce_get_product($item, $currency);
$order->add_product( $product, $item['quantity']);
}
$order->set_address( $billing_address, 'billing' );
$order->set_address( $shipping_address, 'shipping' );
$order->set_currency( $currency );
$order->set_payment_method( $order_data['payment_method'] );
$order->calculate_totals();
$order->calculate_taxes();
// Előfizetés
foreach ($order_data['ordered_items'] as $item) {
if (WC_Subscriptions_Product::is_subscription($item['id'])) {
$product = wce_get_product($item, $currency);
$sub = wcs_create_subscription(array('order_id' => $order->id, 'billing_period' => $period, 'billing_interval' => $interval, 'start_date' => $start_date));
$sub->add_product( $product, $item['quantity']/*, $args*/);
$sub->set_address( $billing_address, 'billing' );
$sub->set_address( $shipping_address, 'shipping' );
$sub->calculate_totals();
}
}
$payment_link = $order->get_checkout_payment_url();
return $payment_link;
}

Check if cart have active subscriptions in YITH WooCommerce Subscription Wordpress

I am using YITH WooCommerce Subscription and I want to check if in my cart has subscription I want to disable one of my payment gateway. How could I do ?
I already try this code but this is doesn't work.
add_filter( 'woocommerce_available_payment_gateways', 'filter_gateways', 1);
function filter_gateways( $gateways ){
if (has_woocommerce_subscription('','','active')) {
unset( $gateways['pin_payments'] );
}
return $gateways;
}
function has_woocommerce_subscription($the_user_id, $the_product_id, $the_status) {
$current_user = wp_get_current_user();
if (empty($the_user_id)) {
$the_user_id = $current_user->ID;
}
if (WC_Subscriptions_Manager::user_has_subscription( $the_user_id, $the_product_id, $the_status)) {
return true;
}
}
You have 2 questions, one is active subscription that you can test via this function:
function CheckSubscriptionByEmail($email) {
// getting all the records of the user by email for the subscription
$subscriptions = get_posts( array(
'numberposts' => -1,
'post_type' => 'ywsbs_subscription', // Subscription post type
'orderby' => 'post_date', // ordered by date
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_billing_email', //additional fields being used to get the data
'value' => $email,
'compare' => '='
),
array(
'key' => '_status',
'value' => 'active', //active subscriptions
'compare' => '='
))
) );
// check if user has any active subscription
foreach ( $subscriptions as $post ) : setup_postdata( $post );
$nextdue = get_post_meta(get_the_id(), '_payment_due_date',true);
$current_date = date("Y-m-d");
$date_to_compare = date("Y-m-d",strtotime($nextdue));
if (strtotime($date_to_compare) > strtotime($current_date)) {
echo "active"; //returns active
break;
}
endforeach;
wp_reset_postdata();
}
Refernece and Explanation at:
https://makersbyte.com/check-active-subscriptions-using-yith-woocommerce/
If you want to just test all the active subcriptions then change in above function the following:
$subscriptions = get_posts( array(
'numberposts' => -1,
'post_type' => 'ywsbs_subscription', // Subscription post type
'orderby' => 'post_date', // ordered by date
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_status',
'value' => 'active', //active subscriptions
'compare' => '='
))
) );
Once you have the list of active subscription, it be fairly straight and simple to disable them if needed.
Payment Gateway, simply goto Woocommerce -> Checkout > All payment gateways are listed in it. Use it to disable.

How to random order a user list with get_users

I actually have a "users" page ordered by post_count.
I'm wondering if is possible to order the list randomly. I know that the get_usersfunction just allows ordering by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', 'post_count', 'include',or'meta_value'
For get_posts, if I remember well, there is a rand option to achieve this.
Here's the code of my template:
<?php
/*
Template Name: Display Contributors and Authors
*/
$args = array(
'role' => 'contributor',
'orderby' => 'post_count',
'order' => 'DESC'
);
// only return users with published posts
$args['has_published_posts'] = true;
// run the WP_Query
$contributors = get_users( $args );
?>
You can use following code to register order by rand:
add_action( 'pre_user_query', 'my_random_user_query' );
function my_random_user_query( $class ) {
if( 'rand' == $class->query_vars['orderby'] )
$class->query_orderby = str_replace( 'user_login', 'RAND()', $class->query_orderby );
return $class;
}
And then use it like this:
$args = array(
'role' => 'contributor',
'orderby' => 'rand',
'order' => 'DESC'
);
Source

Attach image to post in Wordpress XMLRPC

I am using XMLRPC to do posts to Wordpress. I am having issues posting thumbnails, after debugging wordpress code I see that my issue is caused by the fact that the image is not attached to the post.
I must do this without patching wordpress or using PHP, only iwth XMLRPC.
I can upload an image and get the ID of the image.
Other point that confuses me is how do you attach an image to a post that you did not posted yet because you wait for the image to upload? I am supposed to upload image then post ,then using the image id and the post id do an update on the image metadata?
Edit: the code in wordpress that is problematic is this check
if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
and my assumption it is that it fails because the image is Unattached, if i fix that code all is fine but I can't patch the WP of my application users(so this is not a solution)
Yes it is possible to do it, if Wordpress version is 3.5 or greater,when using the code for uploading file/image you can set the post_id.
The flow I used for new posts with featured images is like this:
use the newPost function and post the content without the featured
image and also set publish to false, record the post_id returned by
this
upload the image and set the post_id to the id of the post just
posted, record the image_id
when done edit the post and set the wp_post_thumbnail equal to the
image_id you just uploaded and also set publish to true(if needed)
Important:
The mime type is important, it must be "image/jpg" or "image/png" please see documentation, if mime type is worng like "jpg" attaching will fail.
Tip:
For debugging, if you get a generic error from wordpress and you can't figure out why you can check the wordpress code and even edit it, adding debugging/tracing calls and hopefully you can figure out the cause.
This is an example of a post with category, image and tags. It requires class-IXR.php
https://github.com/WordPress/WordPress/blob/master/wp-includes/class-IXR.php
and mime_content_type function
https://github.com/caiofior/storebaby/blob/master/magmi/plugins/extra/general/socialnotify/wp/mimetype.php
$client = new IXR_Client($url);
$content = array(
'post_status' => 'draft',
'post_type' => 'post',
'post_title' => 'Title',
'post_content' => 'Message',
// categories ids
'terms' => array('category' => array(3))
);
$params = array(0, $username, $password, $content);
$client->query('wp.newPost', $params);
$post_id = $client->getResponse();
$content = array(
'name' => basename('/var/www/sb/img.jpeg'),
'type' => mime_content_type('/var/www/sb/img.jpeg'),
'bits' => new IXR_Base64(file_get_contents('/var/www/sb/img.jpeg')),
true
);
$client->query('metaWeblog.newMediaObject', 1, $username, $password, $content);
$media = $client->getResponse();
$content = array(
'post_status' => 'publish',
// Tags
'mt_keywords' => 'tag1, tag2, tag3',
'wp_post_thumbnail' => $media['id']
);
$client->query('metaWeblog.editPost', $post_id, $username, $password, $content, true);
My version if you want to use only wp.newPost and wp.editPost
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
$usr = 'username_on_the_server_side';
$pwd = 'password_on_the_server_side';
$xmlrpc = 'server side xmlrpc.php url';
$client = new IXR_Client($xmlrpc);
//////////// IMAGE UPLOAD AND ATTACHMENT POST CREATION ///////////
$img_attach = 'link to the image';
$img_attach_content = array(
'name' => basename($img_attach),
'type' => mime_content_type($img_attach),
'bits' => new IXR_Base64(file_get_contents($img_attach)),
);
$status = $client->query( 'wp.uploadFile','1', $usr, $pwd, $img_attach_content );
$image_returnInfo = $client ->getResponse();
//////////// POST CREATION ///////////
$custom_fields = array(
array( 'key' => 'blabla1', 'value' => 'blabla1_value' ),
array( 'key' => 'blabla12', 'value' => 'blabla1_value2')
);
$post_content = array(
'post_type' => 'post',
'post_status' => 'draft', //for now
'post_title' => 'XMLRPC Test',
'post_author' => 3,
'post_name' => 'XMLRPC Test',
'post_content' => 'XMLRPC Test Content',
'custom_fields' => $custom_fields
);
$res = $client -> query('wp.newPost',1, $usr, $pwd, $post_content);
$postID = $client->getResponse();
if(!$res)
echo 'Something went wrong....';
else {
echo 'The Project Created Successfully('.$res.')<br>Post ID is '.$postID.'<br>';
}
//////////// Image Post Attachment Edit ///////////
$img_attach_content2 = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_title' => $postID,
'post_name' => $postID,
'post_parent' => $postID,
'guid' => $image_returnInfo['url'],
'post_content' => '',
'post_mime_type' => 'image/jpg'
);
$res2 = $client -> query('wp.editPost', 0, $usr, $pwd, $image_returnInfo['id'], $img_attach_content2);
$postIDimg = $client->getResponse();
//////////// POST EDIT ///////////
$post_content2 = array(
'post_status' => 'publish', //publish
'wp_post_thumbnail' => $image_returnInfo['id'],
'custom_fields' => array( 'key' => '_thumbnail_id', 'value' => $image_returnInfo['id'] )
);
$media2= $client->query('wp.editPost',0, $usr, $pwd, $postID, $post_content2);
This is my version, using wp.newPost and wp.editPost, added on WordPress 3.4, that allow the use of custom post types.
require_once("IXR_Library.php.inc");
$title = 'My title';
$body = 'My body';
$category="category1, category2"; // Comma seperated pre existing categories. Ensure that these categories exists in your blog.
$keywords="keyword1, keyword2, keyword3";
$customfields=array('key'=>'Author-bio', 'value'=>'Autor Bio Here'); // Insert your custom values like this in Key, Value format
$title = htmlentities($title,ENT_NOQUOTES,#$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,#$encoding);
$content = array(
'post_title'=>$title,
'post_content'=>$body,
'post_type'=>'some_custom_post_type',
'post_status' => 'draft', // http://codex.wordpress.org/Post_Status
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'mt_keywords'=>$keywords,
'categories'=>array($category),
'custom_fields' => array($customfields)
);
// Create the client object
$client = new IXR_Client('http://example.com/xmlrpc.php');
$username = "wp_username";
$password = "wp_username_password";
$params = array(0,$username,$password,$content,true); // Last parameter is 'true' which means post immediately, to save as draft set it as 'false'
if (!$client->query('wp.newPost', $params)) {
die('<br/><strong>Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage().'<br >');
}
else
{
$post_id = $client->getResponse();
echo 'Inserted with id'.$post_id;
$picture = '/full/path/to/pic.jpg';
$content = array(
'name' => basename($picture),
'type' => mime_content_type($picture),
'bits' => new IXR_Base64(file_get_contents($picture)),
true
);
if (!$client->query('metaWeblog.newMediaObject', 1, $username, $password, $content)) {
die('<br/><strong>Something went wrong - newMediaObject'.$client->getErrorCode().' : '.$client->getErrorMessage().'<br >');
}
else
{
$media = $client->getResponse();
$content = array(
'post_status' => 'publish',
'post_thumbnail' => $media['id']
);
if (!$client->query('wp.editPost', 0, $username, $password, $post_id, $content)) {
die('<br/><strong>Something went wrong editPost - '.$client->getErrorCode().' : '.$client->getErrorMessage().'<br >');
}
}
}

Resources