Issues with Post Title Generation Using Custom Table Data

Support MB Custom Table Issues with Post Title Generation Using Custom Table DataResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #47458
    Simon EgleSimon Egle
    Participant

    We are using the Metabox plugin, specifically the MB Custom Table extension, to store custom data in a custom table (wp_person). The goal is to automatically generate a post title for a custom post type (veranstalter) using two custom fields, person_vorname and person_nachname, stored in the custom table.

    Current Setup:
    1. We have a custom post type called veranstalter.
    2. The custom table wp_person contains two fields: person_vorname and person_nachname.
    3. The title for the veranstalter post should be generated by combining the values of person_vorname and person_nachname from the custom table.
    4. The table is properly set up and data for person_vorname and person_nachname is available, but there is an issue with retrieving the data and updating the post title.

    The Issue:
    • We are using the save_post action hook to retrieve the values from the custom table based on the post ID and then try to update the post title.
    • However, the data is not always being retrieved correctly, and we are encountering errors like “No data found for post ID” or “First name or last name is empty.”
    • We also tried adding delays and checked if the custom table data is accessible using raw SQL queries, but the issue persists.

    Our Code:

    add_action('save_post', function ($post_id) {
        // Safety checks to prevent unnecessary or repeated executions
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
    
        if (wp_is_post_revision($post_id)) {
            return;
        }
    
        // Check if the correct post type is being saved
        if (get_post_type($post_id) !== 'veranstalter') {
            return;
        }
    
        // Prevent recursive calls by using a flag
        static $is_updating = false;
        if ($is_updating) {
            return;
        }
    
        // Retrieve custom field data from the custom table
        global $wpdb;
        $table_name = $wpdb->prefix . 'person';
        $sql = $wpdb->prepare("SELECT person_vorname, person_nachname FROM $table_name WHERE ID = %d", $post_id);
        $result = $wpdb->get_row($sql);
    
        // Check if the data is found
        if ($result) {
            $vorname = $result->person_vorname;
            $nachname = $result->person_nachname;
    
            // Only generate title if both fields have values
            if (!empty($vorname) && !empty($nachname)) {
                $is_updating = true; // Set flag to prevent recursion
    
                // Generate title from Vorname and Nachname
                $title = trim("$vorname $nachname");
    
                // Generate a unique slug for the post
                $unique_slug = wp_unique_post_slug(sanitize_title($title), $post_id, 'publish', 'veranstalter', 0);
    
                // Update the post title and slug
                wp_update_post([
                    'ID'         => $post_id,
                    'post_title' => $title,
                    'post_name'  => $unique_slug,
                ]);
    
                $is_updating = false; // Reset flag
            }
        } else {
            // Log if no data is found for the provided post_id
            error_log("No data found for post_id $post_id in the custom table.");
        }
    });

    Our Question:
    • Is there a recommended approach to automatically update the post title using custom table data in Metabox?
    • Are there any other solutions or workarounds for this type of situation?
    • Is there a way to ensure that data is reliably retrieved and the title is updated without issues?

    We would appreciate any advice or insights on how to solve this issue more effectively.

    #47468
    PeterPeter
    Moderator

    Hello,

    I think that the callback function runs at the action hook save_post won't get the correct field value because custom field values are saved after saving the post. I suggest you:

    1. Use the helper function rwmb_meta() to get the field value that is saved to the custom table
    https://docs.metabox.io/extensions/mb-custom-table/#getting-field-value

    2. Or use the action hook rwmb_{$field_group_id}_after_save_post to ensure all field values are saved.
    https://docs.metabox.io/actions/rwmb-after-save-post/
    Reference https://support.metabox.io/topic/adding-metabox-field-data-to-the-post-title/

    3. Or get the field value from the global variable $_POST.

    I hope that helps.

    #47480
    Simon EgleSimon Egle
    Participant

    Hi Peter,

    Thank you so much for your prompt and helpful response! Your guidance was spot on, and using the rwmb_meta() function worked perfectly for our use case. We’re grateful for the detailed explanation and the resources you shared. 🙏

    For anyone who might face a similar issue in the future, here’s the working code that generates a post title from custom fields stored in a custom table created with Metabox. This example is for a custom post type called veranstalter with the fields person_vorname and person_nachname in the custom table.

    <?php
    // Hook into Metabox's action after all custom fields in the "person" field group are saved
    add_action('rwmb_person_after_save_post', function ($post_id) {
        // Ensure this only runs for the custom post type "veranstalter"
        if (get_post_type($post_id) !== 'veranstalter') {
            return;
        }
    
        // Use rwmb_meta() to retrieve values directly from the custom table
        $first_name = rwmb_meta('person_vorname', '', $post_id);
        $last_name = rwmb_meta('person_nachname', '', $post_id);
    
        // Check if both fields have values
        if (!empty($first_name) && !empty($last_name)) {
            // Generate the title by combining first and last name
            $title = trim("$first_name $last_name");
    
            // Generate a unique slug for the post
            $unique_slug = wp_unique_post_slug(sanitize_title($title), $post_id, 'publish', 'veranstalter', 0);
    
            // Update the post title and slug
            wp_update_post([
                'ID'         => $post_id,
                'post_title' => $title,
                'post_name'  => $unique_slug,
            ]);
        } else {
            error_log("First name or last name is missing for post_id $post_id");
        }
    });
Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.