Support Log in

11. Registering Custom Post Types for Translation

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

Lang Forge can translate any custom post type. By default, only post and page are enabled. Register your custom post types for translation either through the admin or programmatically.

Enabling via Filter

php
/**
 * Add custom post types to the translatable list.
 *
 * @param array $post_types Array of post type slugs
 * @return array Modified array
 */
add_filter('lf_translatable_post_types', function ($post_types) {
    $post_types[] = 'portfolio';
    $post_types[] = 'testimonial';
    $post_types[] = 'event';
    return $post_types;
});
ParameterTypeDescription
$post_typesarrayArray of post type slugs currently enabled for translation
Return TypeDescription
arrayModified array of post type slugs

Enabling via Options

php
// Programmatically enable a post type
$translatable = get_option('lf_translatable_post_types', []);
if (!in_array('portfolio', $translatable)) {
    $translatable[] = 'portfolio';
    update_option('lf_translatable_post_types', $translatable);
}

Registering a Translation-Ready Custom Post Type

When registering your custom post type, ensure it has show_in_rest for REST API support and proper rewrite rules for language prefixes:

php
add_action('init', function () {
    register_post_type('portfolio', [
        'label'        => 'Portfolio',
        'public'       => true,
        'show_in_rest' => true,
        'has_archive'  => true,
        'rewrite'      => ['slug' => 'portfolio'],
        'supports'     => ['title', 'editor', 'thumbnail', 'excerpt'],
    ]);
});

// Enable it for translation
add_filter('lf_translatable_post_types', function ($types) {
    $types[] = 'portfolio';
    return $types;
});
Example: Creating translations for a custom post type programmatically
php
// Create a portfolio item and its English translation
$ru_post_id = wp_insert_post([
    'post_type'   => 'portfolio',
    'post_title'  => 'Мой проект',
    'post_status' => 'publish',
]);

LF_Post_Translation::instance()->set_post_language($ru_post_id, 'ru');

$en_post_id = wp_insert_post([
    'post_type'   => 'portfolio',
    'post_title'  => 'My Project',
    'post_status' => 'publish',
]);

LF_Post_Translation::instance()->set_post_language($en_post_id, 'en');

// Link them as translations
LF_Post_Translation::instance()->link_translations($ru_post_id, $en_post_id);
Example: Verify which post types are translatable
php
// Check if a post type is enabled for translation
$translatable = get_option('lf_translatable_post_types', []);
if (in_array('product', $translatable)) {
    // WooCommerce products are translatable
}

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