Support Log in

13. Translating Custom Fields Programmatically

Developer Guide
Prefer video? Watch the Lang Forge tutorials 9 short guides covering every feature Watch

When you need to copy or sync custom fields across translations beyond what Lang Forge handles automatically.

Copying Custom Meta on Translation Creation

php
/**
 * Copy specific meta fields when a translation is created.
 * Hook into lf_translation_created to extend the default behavior.
 */
add_action('lf_translation_created', function ($original_id, $new_id, $lang) {
    // Define which meta keys to copy
    $meta_keys_to_copy = [
        '_custom_subtitle',
        '_custom_cta_text',
        '_custom_sidebar_text',
    ];

    foreach ($meta_keys_to_copy as $key) {
        $value = get_post_meta($original_id, $key, true);
        if ($value !== '' && $value !== false) {
            update_post_meta($new_id, $key, $value);
        }
    }
}, 10, 3);
Example: Sync non-translatable fields across all translations
php
/**
 * When a "layout" or "color" field is saved, sync it to all translations.
 * These fields are the same across all languages.
 */
add_action('save_post', function ($post_id) {
    if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) return;

    $non_translatable_keys = ['_page_layout', '_accent_color', '_sidebar_position'];
    $translations = lf_get_post_translations($post_id);
    $current_lang = lf_get_post_language($post_id);

    foreach ($non_translatable_keys as $key) {
        $value = get_post_meta($post_id, $key, true);
        if ($value === '' || $value === false) continue;

        foreach ($translations as $lang => $trans_id) {
            if ($lang === $current_lang) continue;
            update_post_meta($trans_id, $key, $value);
        }
    }
}, 20);
Example: Read a custom field with language fallback
php
/**
 * Get a meta value with fallback to the source language post.
 *
 * @param int    $post_id  Post ID
 * @param string $meta_key Meta key
 * @return mixed Meta value, falling back to source language if empty
 */
function theme_get_meta_with_fallback($post_id, $meta_key) {
    $value = get_post_meta($post_id, $meta_key, true);
    if ($value !== '' && $value !== false) {
        return $value;
    }

    // Fallback: find the source language post
    $translations = lf_get_post_translations($post_id);
    $default_lang = lf_get_default_language();

    if (isset($translations[$default_lang]) && $translations[$default_lang] !== $post_id) {
        return get_post_meta($translations[$default_lang], $meta_key, true);
    }

    return $value;
}

// Usage
$subtitle = theme_get_meta_with_fallback(get_the_ID(), '_custom_subtitle');

Forge AI Assistant Online

Hi! I'm the Lang Forge AI assistant. Ask me anything about the plugin — setup, features, troubleshooting, or development.

Just now
Powered by Forge AI · Browse docs