don't add wordpress post "meta_input" if it is empty - php

I have this query to insert a new post:
$new_post_args = array(
'post_title' => empty($esc_title = wp_filter_nohtml_kses(wp_trim_words($_POST['text'], 10))) ? 'No Title' : $esc_title,
'post_content' => esc_textarea($_POST['text']),
'post_name' => sanitize_title($_POST['text']),
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_category' => array($_POST['category']),
'comment_status' => $_POST['comments']
);
$new_post_args['meta_input']['_thumbnail_id'] = $_POST['images'][0];
if (count($_POST['images']) > 1) {
unset($_POST['images'][0]);
$new_post_args['meta_input']['gallery_images'] = implode(",", $_POST['images']);
$new_post_args['meta_input']['slider_mode'] = 'horizontal';
$new_post_args['meta_input']['slider_auto'] = 'on';
$new_post_args['meta_input']['slider_pause'] = '3000';
$new_post_args['tax_input'] = array('post_format' => 'gallery');
} else {
if ($_POST['do'] == 'update-post') {
$new_post_args['meta_input']['gallery_images'] = '';
$new_post_args['meta_input']['slider_mode'] = '';
$new_post_args['meta_input']['slider_auto'] = '';
$new_post_args['meta_input']['slider_pause'] = '';
$new_post_args['tax_input'] = array('post_format' => 0);
}
}
if ($_POST['do'] == 'update-post') {
$new_post_args['ID'] = $_POST['id'];
$new_post_id = wp_update_post($new_post_args);
} elseif ($_POST['do'] == 'share-post') {
$new_post_id = wp_insert_post($new_post_args);
}
For posting action, only if the gallery images > 1 then the gallery meta args will be added, but on update-post action I need to delete the args, not to add them empty '' , I don't want to delete_post_meta after the post is published, I'm looking for a way to hook all meta values of the post and do not add them if they are empty, if this is possible I appreciate sharing the code.
Thanks.

Related

Wordpress: Add Interger to User_nicename if it Exists in Database

I have created a Wordpress site where users register on the front-end and add information about themselves. On registration I am forcing the user_nicename to be name-surname. I am then automatically creating 2 custom post types that act as profile pages for the new users. I am using the user_nicename as the title of both.
The problem is obviously if two people register with the same name.
So I would like to check the database before the user_nicename is updated to check if it already exists. If it does I would like to add an integer (in sequence) to the end of the user_nicename.
For instance:
John-Smith
John-Smith-2
John-Smith-3
Etc.
The code I have tried is as follows, but I'm not having any luck. The custom post types generate fine, but the user_nicename is not being appended with an integer.
Any help would be much appreciated!
add_action( 'user_registration_after_register_user_action', 'ur_insert_username', 1, 3 );
function ur_insert_username( $valid_form_data, $form_id, $user_id ) {
global $wpdb;
$firstname = isset( $valid_form_data['first_name'] ) ? $valid_form_data['first_name']->value : '';
$lastname = isset( $valid_form_data['last_name'] ) ? $valid_form_data['last_name']->value : '';
{
$custom_nicename = sanitize_title_with_dashes( $firstname . '-' . $lastname);
{
$i = 1;
do {
$user = get_user_by('login', $custom_nicename);
if( ! empty( $user ) ) {
$i++;
$custom_nicename = $custom_nicename ."-" . $i;
}
}
while ( ! empty( $user ) );
}
$wpdb->update(
$wpdb->users,
['user_nicename' => $custom_nicename],
['ID' => $user_id]
);
}
{
$user_post_athlete = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_id
);
$user_post_rivalry = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'rivalry', // <- change to your cpt
'post_author' => $user_id
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post_athlete );
$post_id = wp_insert_post( $user_post_rivalry );
}
}
I will suggest you to manage post type for user profile using post_author.
I guess you are adding post by code using wp_insert_post , so add "post_author" field to store user id in it. Wordpress will automatically manage slug of two different posts with same title. And you can associate posts and user using "post_author" field.
https://developer.wordpress.org/reference/functions/wp_insert_post/
Editing my answer
get_user_by('login' will not work reason being login is 'username' and you need to search 'nickname'. You need to get user details by below code
$user_data=get_users(array(
'meta_key' => 'nickname',
'meta_value' => 'jaytesh'
));
echo "user id is".$user_data[0]->ID;
And Your code will change to (approx code)
add_action( 'user_registration_after_register_user_action', 'ur_insert_username', 1, 3 );
function ur_insert_username( $valid_form_data, $form_id, $user_id ) {
global $wpdb;
$firstname = isset( $valid_form_data['first_name'] ) ? $valid_form_data['first_name']->value : '';
$lastname = isset( $valid_form_data['last_name'] ) ? $valid_form_data['last_name']->value : '';
{
$custom_nicename = sanitize_title_with_dashes( $firstname . '-' . $lastname);
{
$i = 1;
do {
$user_data=get_users(array(
'meta_key' => 'nickname',
'meta_value' => $custom_nicename
));
if( ! empty( $user_data[0]->ID ) ) {
$i++;
$custom_nicename = $custom_nicename ."-" . $i;
}
}
while ( ! empty( $user_data[0]->ID ) );
}
$wpdb->update(
$wpdb->users,
['user_nicename' => $custom_nicename],
['ID' => $user_id]
);
}
{
$user_post_athlete = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_id
);
$user_post_rivalry = array(
'post_title' => $custom_nicename,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'rivalry', // <- change to your cpt
'post_author' => $user_id
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post_athlete );
$post_id = wp_insert_post( $user_post_rivalry );
}
}

how do I get a post to multi-site of wordpress in php?

I wanna post to multi-site of word-press in php
this code can make it but only to a main-wordpress below
this is not possible for multi-site
so I need to make it post to other multi-site
who can teach me how I can make and change code in php?
or I have to edit other files like wp-load.php or wp-config.php?
function autoPost($title, $desc) {
require_once("/var/www/html/wordpress/wp-load.php");
/*******************************************************
** explanation
*******************************************************/
$postType = 'post'; // post or page
$userID = 2; // user setting
$categoryID = '2'; // categoty number
$postStatus = 'publish';
$leadTitle = $title;
$leadContent = $desc;
$timeStamp = date('Y-m-d H:i:s', strtotime("+9 hour"));
$new_post = array(
'post_title' => $leadTitle,
'post_content' => $leadContent,
'post_status' => $postStatus,
'post_date' => $timeStamp,
'post_author' => $userID,
'post_type' => $postType,
'post_category' => array($categoryID)
);
$post_id = wp_insert_post($new_post);
$finaltext = '';
if($post_id){
$finaltext .= 'successful<br>';
} else{
$finaltext .= 'fail!<br>';
}
echo $finaltext;

Question mark and equals sign not showing up in wordpress post_name

So I want to add the following ?matchPostId=$matchId in post_name on wordpress using wp_insert_post();
I tried using urlencode(); and urldecode(); but still can't get it to work, checked everywhere but seems like the question mark and equals sign is always slashed out in the url of my post. Does anyone know why it does that?
Here is my code:
$questionm = '?';
$equalsm = '=';
$tipsPage = $questionm . 'matchPostId' . $equalsm . $matchId;
$post_idpost = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 1,
'post_name' => $tipsPage,
'post_title' => $value['test']
'post_status' => 'publish',
'post_type' => 'post',
'post_content' => "test"
)
);
Also tried this:
$questionm = ('?');
$equalsm = ('=');
urlencode($questionm);
urlencode($equalsm);
$post_idpost = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 1,
'post_name' => urldecode($questionm) . 'matchPostId' . urldecode($equalsm) . $matchId,
Same problem, the question mark and equals sign is removed from the url.
WP sanitizes postname in the wp_insert_post function.
if ( empty($post_name) ) {
if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
$post_name = sanitize_title($post_title);
} else {
$post_name = '';
}
} else {
// On updates, we need to check to see if it's using the old, fixed sanitization context.
$check_name = sanitize_title( $post_name, '', 'old-save' );
if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
$post_name = $check_name;
} else { // new post, or slug has changed.
$post_name = sanitize_title($post_name);
}
}
Source: http://hookr.io/functions/wp_insert_post/ circa line 3094

How to create Wordpress posts from external json file?

Here is the code I am using. It creates duplicate post every time I refresh. Also, how can I add custom field to my post?
My array looks like this:
[{
"featured":"",
"exclusive":"",
"promo_id":"XXX",
"offer_id":"1",
"title" : "Super Cars"
}]
My php code:
<?php
$json = "url";
$response = file_get_contents($json);
$mydecode = json_decode($response);
for ($i = 10; $i < 15; $i++) {
$title = str_replace("&", "&", $mydecode[$i]->title);
$id = $mydecode[$i]->offer_id;
$link = $mydecode[$i]->link;
if( $id === "x" ) {
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'coupon'
);
$post_id = wp_insert_post($new_post);
}
}
?>
The code successfully inserts posts but duplicate every time I refresh.
If anyone can contribute a bit, it would be great!
Update your code to following,
<?php
$json = "http://tools.vcommission.com/api/coupons.php?apikey=xxxxxxxxxx";
$response = file_get_contents($json);
$mydecode = json_decode($response);
for ($i = 0; $i < 15; $i++) {
$title = str_replace("&", "&", $mydecode[$i]->coupon_title);
$description = str_replace("&", "&", $mydecode[$i]->coupon_description);
$store_name = $mydecode[$i]->offer_name;
$coupon_type = $mydecode[$i]->coupon_type;
$coupon_code = $mydecode[$i]->coupon_code;
$link = $mydecode[$i]->link;
$expiry_date = $mydecode[$i]->coupon_expiry;
if( $coupon_type === "Coupon" ) {
// Check if already exists
$get_page = get_page_by_title( $title );
if ($get_page == NULL){
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'coupon'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $post_id, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $get_page->ID, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}
?>
I hope this helps.

Schedule wordpress posts on uploading images

I have the following code that works perfect on creating posts from images on uploading from wordpress dashboard by media uploads, but I need to schedule this posts at a specific interval (30 minutes one new post):
<?php
$autopost_controler = get_theme_mod( 'auto_onoff' );
if( $autopost_controler != '' ) {
switch ( $autopost_controler ) {
case 'on':
add_action('add_attachment', 'auto_post_on_image_upload');
function auto_post_on_image_upload($attachId)
{
$attachment = get_post($attachId);
$image = wp_get_attachment_image_src( $attachId, 'large');
$image_tag = '<p><img src="'.$image[0].'" /></p>';
$cidargs = array('category_name' => get_theme_mod('cat_1'));
$cid = array(get_category_by_slug($cidargs['category_name'])->term_id);
$theoriginaltitle = $attachment->post_title;
$onetitle = str_replace("-"," ",$theoriginaltitle);
$thetitlef = str_replace("_"," ",$onetitle);
$thetitle = ucwords(strtolower($thetitlef));
$content = '<strong>'. $thetitle .' </strong> is a funny photo posted in <strong>'.$cidargs['category_name'].'</strong> category. If you like <strong>'. $thetitle .'</strong> funny image, please share it with your friends.';
$alltags = $thetitle;
$createtags = explode(" ", $alltags);
$postData = array(
'post_title' => $thetitle,
'post_type' => 'post',
'post_content' => $content,
'post_category' => $cid,
'tags_input' => $createtags,
'post_status' => 'publish'
);
$post_id = wp_insert_post($postData);
// attach media to post
wp_update_post(array(
'ID' => $attachId,
'post_parent' => $post_id
));
set_post_thumbnail($post_id, $attachId);
return $attachId;
}
break;
case 'off':
break;
}
}

Categories