Wordpress: Add Interger to User_nicename if it Exists in Database - php

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 );
}
}

Related

How do I display custom post title as "first_name last_name"

I have created a site whereby athletes can register and create their own templated profile page. On registration, I automatically create a custom post (their profile) and set the user as the author of that post.
However, I cannot for the life of me set the post title as the user's (now author's) first name and surname. For instance, if John Smith registers, I would like the post title to read John Smith, and the slug to convert to athlete/john.smith.
I have used $user_info->nickname for now, but this causes both the title and the slug to read as john.smith
This is the code I am using -any pointers would be greatly appreciated:
add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
if ($this_user_role == 'author') {
// Create a new post
$user_post = array(
'post_title' => $user_info->nickname,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_info->ID
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
You should also use post_name for slug(john.smith) and first_name,last name for post title like this:
add_action( 'user_register', 'wpse_216921_company_cpt', 20, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
if ($this_user_role == 'author') {
$post_title = $user_info->first_name.' '.$user_info->last_name;
$post_title = trim(ucwords($post_title));
$post_slug = preg_replace('/\s+/', '.', $post_title);
// Create a new post
$user_post = array(
'post_title' => $post_title, //$user_info->display_name,
'post_name' => $post_slug,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_info->ID
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
You can use firstname and lastname like below:
add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
$first_name = $user_info->first_name;
$last_name = $user_info->last_name;
if ($this_user_role == 'author') {
// Create a new post
$user_post = array(
'post_title' => $first_name . ' ' . $last_name,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_info->ID
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}
Not tested but it should works.
Thanks for the assistance guys. It turned out to be an Ultimate Member issue, and I needed to use the UM Hook um_registration_complete.
The final solution that worked is as follows:
//Create Custom Post Type on registration
add_action( 'um_registration_complete', 'wpse_216921_company_cpt', 10, 1 );
function wpse_216921_company_cpt( $user_id )
{
// Get user info
$user_info = get_userdata( $user_id );
$user_roles = $user_info->roles;
// New code added
$this_user_role = implode(', ', $user_roles );
if ($this_user_role == 'author') {
$post_title = $user_info->first_name.' '.$user_info->last_name;
$post_title = trim(ucwords($post_title));
$post_slug = preg_replace('/\s+/', '.', $post_title);
// Create a new post
$user_post = array(
'post_title' => $post_title, //$user_info->display_name,
'post_name' => $post_slug,
'post_status' => 'publish', // <- here is to publish
'post_type' => 'athlete', // <- change to your cpt
'post_author' => $user_info->ID
);
// Insert the post into the database
$post_id = wp_insert_post( $user_post );
}
}

WP check if custom post title exists before wp_insert_post

I am trying to do a conditional check (checking if post with same post title exists) before running wp_insert_post() but it still accepts the insertion even if existing posts are found. I tried using post_exists(), but this function breaks the entire page for some reason. What am I doing wrong?
footer.php:
<?php
$statusmessage = '';
if (isset($_POST['footer-email'])){
$footer_email = $_POST['footer-email'];
$args = array(
"post_title" => $footer_email,
"post_type" => 'subscriptions',
"post_status" => 'publish',
);
$query = new WP_Query( $args );
if($query->have_posts()) {
$statusmessage = '<p class="subscription-confirmation">You have already signed up.</p>';
}
else {
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
} // end else
wp_reset_postdata();
} // end if isset footer email
?>
You can use post_exists(). check the below cood.
<?php
$statusmessage = '';
if (isset($_POST['footer-email'])){
$footer_email = $_POST['footer-email'];
if( ! post_exists( $footer_email ) ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
} // end if isset footer email
You can use get_page_by_title() to fetch subscribers by title.
$statusmessage = '';
if ( isset( $_POST['footer-email'] ) ){
$footer_email = $_POST['footer-email'];
$subscribers = get_page_by_title( $footer_email , OBJECT, 'subscribers' );
if( !$subscribers->ID ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
}
OR custom wpdb query.
global $wpdb;
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $footer_email . "'" );
if( !$postid ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}

How to update woocommerce order number to a custom ACF field? (wordpress)

I have a custom post called "project", and it has an acf field called "ponum".
When a customer purchases a product, I'd like to add the customer's order number to the "ponum" field of the user’s post in the custom post "project".
Getting an order number & creating a post works, but I have no idea how to add this number to the acf field on a thank you page.
add_action( 'woocommerce_thankyou', 'create_post_on_order' );
function create_post_on_order($order_id)
{
global $wpdb;
//print('<pre>'.print_r( $wpdb, true ).'</pre>');
$order = wc_get_order($order_id);
if (!$order->get_id()) {
return;
}
$current_user = wp_get_current_user();
$current_user_id = $current_user->display_name;
$post_title = $order_id . ' - ' . $current_user_id;
// Check post already exit with our title or not
$query = $wpdb->prepare(
'SELECT ID FROM ' . $wpdb->posts . '
WHERE post_title = %s
AND post_type = \'project\'',
$post_title
);
$wpdb->query($query);
if (!$wpdb->num_rows) {
$post_id = wp_insert_post(
array(
'author' => $current_user_id,
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'project'
)
);
}
}
Would you please help me?
Thank you.
Once you have the value for your acf (i.e "$order_id"), then you could use the following code to update the acf field:
UPDATED ANSWER BASED ON YOUR NEW CODE
add_action('woocommerce_thankyou', 'create_post_on_order');
function create_post_on_order($order_id)
{
$order = wc_get_order($order_id);
if (!$order->get_id()) {
return;
}
$current_user = get_userdata(get_current_user_id());
$current_user_name = $current_user->display_name;
$post_title = $order_id . ' - ' . $current_user_name;
$query = new WP_Query(array(
"author" => get_current_user_id(),
"post_type" => "project",
"title" => $post_title
));
if ($query->found_posts == 0) {
$post_id = wp_insert_post(
array(
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'project',
"meta_input" => array(
"ponum" => $order_id
)
)
);
// It should work without this, this is just a double check!
if (get_post_type($post_id) == "project") {
$ponum_key = 'ponum';
$ponum_field_value = get_field($ponum_key);
if (empty($ponum_field_value)) {
$ponum_field_value = $order_id;
update_field($ponum_key, $ponum_field_value);
}
}
}
}

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

WordPress: Convert comments to Posts when approved

I'm using the function below to convert WP-comments to WP-posts. I want it to be fired when "approving" a comment. (now it is whenever the plug-in is activated in WP).
So really I'm wondering how to ad my function to this action from line 47 of the edit-comments.php:
foreach ( $comment_ids as $comment_id ) { // Check the permissions on each
if ( !current_user_can( 'edit_comment', $comment_id ) )
continue;
switch ( $doaction ) {
case 'approve' :
wp_set_comment_status( $comment_id, 'approve' );
$approved++;
break;
[...]
}
}
Plug-in function:
register_activation_hook( __FILE__, 'convert_to_posts' );
function convert_to_posts(){
$comments = get_comments();
foreach($comments as $comment)
{
$post = get_post($comment->comment_post_ID);
$title = get_comment_meta( $comment->comment_ID, 'title', true );
$content = $comment->comment_content;
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1
);
wp_insert_post( $my_post );
// wp_delete_comment( $comment->comment_ID );
}
}

Categories