Problem: I would like to automatically connect multiple posts in a M2M relationship. The GUI lets me connect each post manually, but I would like to automate the process. I would like to query all the posts in one custom post type, which have one specific taxonomy term, and relate those posts to 3 specific posts from another custom post type.
Solution:
Create a backup of your site and database first. Then insert this code in functions.php. This code creates a shortcode which calls a custom get_posts query to get the posts in one specific category, and uses the toolset_connect_posts API to loop over each of those posts and connects it to all 3 posts in the other custom post type. Place the shortcode on a page, then load the page once in the front-end. Finally remove the code from functions.php and remove the shortcode from the page. Custom code follows:
add_shortcode('ts_update_db_relationships', 'ts_update_db_relationships_func'); function ts_update_db_relationships_func($args) { $pid = 34596; $field = '_ts_cc_wpv_manual_rel_assignment'; $is_updated = get_post_meta( $pid, $field, true); if( $is_updated != 1 ) { $tArgs = array( 'post_type' => 'tecaj', 'numberposts' => -1, 'tax_query' => array( array( 'taxonomy' => 'tip-tecaja', 'field' => 'slug', 'terms' => 'skupinski-tecaji', ), ), ); $tPosts = get_posts($tArgs); $tIds = array(); foreach( $tPosts as $tPost ) { $tIds[] = $tPost->ID; } $cIds = array(34821, 34820, 34814); foreach($tIds as $tId) { foreach($cIds as $cId) { toolset_connect_posts( 'tecaj_cena', $tId, $cId ); } } wp_reset_query(); update_post_meta( $pid, $field, 1 ); } return ''; }
Relevant Documentation:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/
https://codex.wordpress.org/Template_Tags/get_posts
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 |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 6 replies, has 2 voices.
Last updated by 6 years, 5 months ago.
Assisted by: Christian Cox.