Let's say I have a custom post type called 'book' and its custom field is 'book-url'. Now I want to set the value of 'book-url' to 'hidden link' for all of the posts of 'book' post type. But I don't want to go to all of the book posts one by one and change it. Because there are thousands of posts in book posts. So it will be very time consuming. Also, as far as I know, Toolset Types doesn't have any API.
So I need a custom code which will change the value of 'book-url' of all the book posts at once. I will add the custom code to toolset and when I will Run it, it will perform the task. Can you kindly give me the code?
Hi there,
You can use the code below:
function update_book_urls() {
// Get all posts of the 'book' post type
$args = array(
'post_type' => 'book',
'posts_per_page' => -1,
);
$book_posts = get_posts( $args );
// Loop through each post and update the 'book-url' custom field
foreach ( $book_posts as $post ) {
update_post_meta( $post->ID, 'wpcf-book-url', '<em><u>hidden link</u></em>' );
}
}
add_action( 'init', 'update_book_urls' );
This code defines a function called update_book_urls() that gets all posts of the book post type and updates the wpcf-book-url custom field to "hidden link". The function is then added as a callback to the init action using the add_action() function.
This way, whenever the init action is fired, the update_book_urls() function will be executed and update the wpcf-book-url custom field for all book posts.
After that, just load the website homepage once. And then all the values will be the URL in question, even the ones that have other value.
Now you can remove the code from functions.php so that you can start adding other values if you want.
Do not run this code without having a backup of your database.
Please consider that all Toolset custom fields have wpcf- prefix on them when you want to use a custom code to retrieve them.
Thanks.
I don't want to load the homepage to update the custom field. Rather I want to run the code using the Run Now option in Custom Code.
So I changed a few things in the code.
function update_book_urls($post_type, $url) {
// Get all posts of the 'book' post type
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1,
);
$book_posts = get_posts( $args );
// Loop through each post and update the 'book-url' custom field
foreach ( $book_posts as $post ) {
update_post_meta( $post->ID, 'wpcf-saas-deal-link', $url );
}
}
update_book_urls('saas', '<em><u>hidden link</u></em>');
Will this code work?
Hi there,
Yes it should work. Please have a backup before testing.
Thanks.
My issue is resolved now. Thank you!