Skip Navigation

[Resolved] Function user field in other type

This thread is resolved. Here is a description of the problem and solution.

Problem:

The customer wanted to display the value of the "Date of birth" user field in a custom post type called "publication." They were looking for a way to do this through a function rather than a shortcode, as publications are added via a Toolset CRED form.

Solution:

To achieve this, the customer was advised to follow a three-step process:

1- Create a Custom Field:
They needed to create a custom field in their "publication" post type to store the user's date of birth. This field could be named birth-post-field.

2- Populate Existing Posts:
A custom function was provided to loop through existing posts and retrieve the date of birth from the user meta. The code snippet provided was:

function update_birth_field_for_existing_posts() {
    // Replace 'your_custom_post_type' with your actual CPT slug
    $custom_post_type = 'your_custom_post_type';
    
    // Query to get all posts of the specified custom post type
    $query_args = array(
        'post_type'      => $custom_post_type,
        'posts_per_page' => -1, // Retrieve all posts
        'post_status'    => 'publish', // Only published posts
        'fields'         => 'ids' // We only need the post IDs
    );

    // Execute the query
    $posts = get_posts($query_args);

    // Loop through each post
    foreach ($posts as $post_id) {
        // Get the post author ID
        $author_id = get_post_field('post_author', $post_id);

        // Get the 'birth' custom field value for the author
        $client_birth = get_user_meta($author_id, 'wpcf-birth', true);

        // Check if the author has a 'birth' value
        if (!empty($client_birth)) {
            // Update the post meta with the user's birth value
            update_post_meta($post_id, 'wpcf-birth-post-field', sanitize_text_field($client_birth));
        }
    }

    // Remove the action after it runs to prevent it from running multiple times
    remove_action('admin_init', 'update_birth_field_for_existing_posts');
}

// Hook the function to admin_init so it runs when any admin page is accessed
add_action('admin_init', 'update_birth_field_for_existing_posts');

This code should be added to the theme's functions.php file and executed once by accessing the WordPress admin dashboard.

3- Automatically Populate on New Posts:
Another function was provided to ensure that when new publications were created or edited through the CRED form, the user's date of birth would automatically populate in the custom field:

add_action('cred_save_data', 'my_save_user_birth_to_post', 10, 2);

function my_save_user_birth_to_post($post_id, $form_data) {
    // Your Toolset form ID in here
    if ($form_data['id']==ID) {
        // Check if the user is logged in
        if (is_user_logged_in()) {
            // Get the current user ID
            $current_user_id = get_current_user_id();
            
            // Get the 'birth' custom field value for the current user
            $clientBirth = get_user_meta($current_user_id, 'wpcf-birth', true);
            
            // Check if the user has a 'birth' value
            if (!empty($clientBirth)) {
                // Save the user's 'birth' value to the post's 'wpcf-birth-post-field' custom field
                update_post_meta($post_id, 'wpcf-birth-post-field', sanitize_text_field($clientBirth));
            }
        }
    }
}

After implementing these steps, the customer would have a new custom field linked to the user's date of birth, ensuring that new posts or edits would sync the user's birthdate with the post field. They would also be able to utilize the post field in views.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 -
- 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 -

Supporter timezone: America/Sao_Paulo (GMT-03:00)

This topic contains 5 replies, has 2 voices.

Last updated by Mateus Getulio 2 months ago.

Assisted by: Mateus Getulio.

Author
Posts
#2745176

Hello,

With a function I would like to display the value of user/author in another post type ?

Thank you

#2745608

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

Hello there,

Is it something similar to what my colleague described here https://toolset.com/forums/topic/get-current-custom-type-post-author-post-id/#post-1678067?

If not, can you please share more information on what you're trying to implement? Are you using blocks or the legacy views? Do you want to display the author info of the current post in the loop?

Thank you, please let me know so I can check the best way of doing it.

#2745634

Hello,

I created user fields with toolset.
Example “Date of birth”

In a type that I named "publication" I would like to have the value of "Date of birth" of the user with a function.

No shortcode.

Thank you.

#2745746

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

Hi there,

So when a user adds or edit a post of the CPT 'publication' you want to store its date-of-birth as a custom field inside 'publication', correct?

How is the user going to add/edit the posts from 'publication', will they use the front end with a Toolset form or the back end to add it?

Thank you, please let me know so I can get the correct example for you.

#2747200

Hello,

I would like to get the value of "date of birth" through a function.

Indeed the publications are added from a CRED form.

Thank you

#2747343

Mateus Getulio
Supporter

Languages: English (English )

Timezone: America/Sao_Paulo (GMT-03:00)

All right,

I think the simplest way of doing it would be to add a custom field to your CPT to mirror the User field birth, then you'll be able to display the user's date of birth through the info available in the CPT field group like a regular custom field.

It involves 3 steps:

1- Create the custom field inside your Post type to mirror the date of birth from the user, let's say we're calling it birth-post-field.
2- Loop your posts from that CPT and make sure all of the old posts have the information from their user responsible from creating them(please replace your post type slug, the date of birth user field with its slug and the new created birth in the CPT):

function update_birth_field_for_existing_posts() {
    // Replace 'your_custom_post_type' with your actual CPT slug
    $custom_post_type = 'your_custom_post_type';
    
    // Query to get all posts of the specified custom post type
    $query_args = array(
        'post_type'      => $custom_post_type,
        'posts_per_page' => -1, // Retrieve all posts
        'post_status'    => 'publish', // Only published posts
        'fields'         => 'ids' // We only need the post IDs
    );

    // Execute the query
    $posts = get_posts($query_args);

    // Loop through each post
    foreach ($posts as $post_id) {
        // Get the post author ID
        $author_id = get_post_field('post_author', $post_id);

        // Get the 'birth' custom field value for the author
        $client_birth = get_user_meta($author_id, 'wpcf-birth', true);

        // Check if the author has a 'birth' value
        if (!empty($client_birth)) {
            // Update the post meta with the user's birth value
            update_post_meta($post_id, 'wpcf-birth-post-field', sanitize_text_field($client_birth));
        }
    }
    
    // Remove the action after it runs to prevent it from running multiple times
    remove_action('admin_init', 'update_birth_field_for_existing_posts');
}

// Hook the function to admin_init so it runs when any admin page is accessed
add_action('admin_init', 'update_birth_field_for_existing_posts');

You can add this code to your theme's functions.php file after making a backup of the site and open the wp-admin dashboard once. After that you can remove the code.

3- Make sure new posts added or edited will have the info populated when the form is submited:

add_action('cred_save_data', 'my_save_user_birth_to_post', 10, 2);

function my_save_user_birth_to_post($post_id, $form_data) {
        // Your Toolset form ID in here
	if ($form_data['id']==ID)
		// Check if the user is logged in
		if (is_user_logged_in()) {
			// Get the current user ID
			$current_user_id = get_current_user_id();
			
			// Get the 'birth' custom field value for the current user
			$clientBirth = get_user_meta($current_user_id, 'wpcf-birth', true);
			
			// Check if the user has a 'birth' value
			if (!empty($clientBirth)) {
				// Save the user's 'birth' value to the post's 'wpcf-birth-post-field' custom field
				update_post_meta($post_id, 'wpcf-birth-post-field', sanitize_text_field($clientBirth));
			}
		}
	}
}

After going through those 3 steps you will:

- Have a new field group that's linked to the user's date of birth
- Make sure that new posts or editions to old posts will sync the user date of birth with the post field you created
- Be able to use the post field regularly when you're creating your views

It is important to replace the slug of the user field, post field and the CPT with the ones you're using. Also, please make sure to edit the form ID with the one you're using for the CPT insert/edit in the front end.