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 );
}
}
Related
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 );
}
}
I have two custom post types with acf fields.
Custom Post_A, which has 2 fields - title / submitted
Custom Post_B, which has 2 fields - title / percent
Both Post_A and B have the same title (which is the logged in user's name) and they already exist.
When a field ‘submitted’ has the value ‘done’ in Post_A, I need to automatically update a ‘percent’ field with a value ‘50’ in Post_B.
I tried the following code but it doesn't update ‘50’ to Post_B.
Would you please correct my code?
$posts = get_posts(array(
'author' => get_current_user_id(),
'posts_per_page' => -1,
'post_type' => 'post_a',
'meta_key' => 'submitted',
'meta_value' => 'done'
));
$the_query = new WP_Query( $posts );
$the_count = count($the_query);
if($the_count>0) {
foreach ($the_query as $is_done){
$my_post = array();
$my_post['post_type'] = 'post_b';
$my_post['post_title'] = the_title();
// Update the post into the database
$field_key = "field_606cb546456343";
$value = "50";
update_field( $field_key, $value);
}
}
Thank you.
You can use save_post_{$post->post_type} action hook that will trigger on specific post type. check the below code.
function update_post_b( $post_id, $post, $update ){
$post_a_title = get_the_title( $post_id );
$posts = array(
'author' => get_current_user_id(),
'posts_per_page' => -1,
'post_type' => 'post_b'
);
$post_b = new WP_Query( $posts );
if( $post_b->have_posts() ){ while ( $post_b->have_posts() ) { $post_b->the_post();
if( $post_a_title == get_the_title() ){
update_post_meta( get_the_ID(), 'percent', 50 );
}
} }
}
add_action( 'save_post_post_a', 'update_post_b', 10, 3 );
USEFUL LINKS
save_post_{$post->post_type}
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);
}
}
}
}
I created plugin for get post title via API on submit. I used simple api request for getting data after via wp_insert_post() function add to DB. But i want check every time on submit to exists title. If there is a new post title then add to the database if not then it will report that 'There are no new posts'
plugin.php
if(isset($_POST['enable'])) {
$url='api/url';
$result = file_get_contents($url);
$resultData = json_decode($result);
foreach ($resultData as $job) {
$post_exists = get_page_by_title( $job->JobTitle, OBJECT, 'post');
if ( post_exists) {
$data = array (
'post_type' => 'post',
'post_title' => $job->JobTitle,
'post_status' => 'publish',
'post_author' => $user_ID
);
$post_id = wp_insert_post( $data );
}
}
echo "Done!";
}
Try this code.
if( isset( $_POST['enable'] ) ) {
$url = 'api/url';
$result = file_get_contents( $url );
$resultData = json_decode( $result );
foreach ($resultData as $job) {
$post_title = sanitize_title( $job->JobTitle );
$post_id = post_exists( $post_title );
if( !$post_id ){
$data = array(
'post_type' => 'post',
'post_title' => $post_title,
'post_status' => 'publish',
'post_author' => $user_ID,
);
$post_id = wp_insert_post( $data );
}else{
//post title exist
}
}
}
You should try this,
This code will return an array of all posts that match the title.
global $wpdb;
$query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title = "'.$post_title.'" AND post_status="publish"');
$post_exists = $wpdb->get_results( $query );
I'm using Advanced custom fields and custom post types ui, I need to generate a post name with the author's name in it, however this just prints "Solicitud", it seem like my variable $autor gets no value, is there any way I can fix this?
function my_pre_save_post( $post_id ) {
$post2 = get_post($post_id);
$autor=$post2->author;
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud' . $autor,
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
And, here is the code I use to create the form, I'm using acf_form:
$current_inv = $_GET['invid'];
/**
* Template Name: Solicit
*/
acf_form_head();
get_header();
?>
<div id="primary">
<div id="content" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php acf_form(array(
'post_id' => 'new',
'field_groups' => array( 243 ),
'submit_value' => 'Crear el ticket'
)); ?>
<?php endwhile; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>
Try using 'post_author' instead of 'author'. And also make sure that WP_Debug is set to TRUE while you're developing.
Here's a long version
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud',
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// Once we save, retrieve the original post so we can take the post_author
$post2 = get_post($post_id);
// Use post_author
$autor = $post2->post_author;
// Update the post with the new title
wp_update_post(array('ID' => $post_id, $post2->post_title . $autor));
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
Slightly shorter version which uses the current logged in user's username.
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
$current_user = wp_get_current_user();
$author = $current_user->user_login; // OR [user_firstname, user_lastname, display_name]
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud' . $author,
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
References:
http://codex.wordpress.org/Class_Reference/WP_Post
http://www.advancedcustomfields.com/resources/tutorials/using-acf_form-to-create-a-new-post/
http://codex.wordpress.org/Function_Reference/wp_get_current_user