detect the language a post is written in

The main language of a post should be saved in a post meta field. There is no way to detect that automatically. Even Google’s heuristics fail regularly with that.

So add a custom field lang and check with …

$language = get_post_meta( get_the_ID(), 'lang', TRUE );

… what language the post was written in.

Update

Here is a very simple example for a language selector. It will be visible on every post type with a Publish metabox.

enter image description here

get_post_meta( get_the_ID(), '_language', TRUE ); 

… will return the post’s language if available.

add_action( 'post_submitbox_misc_actions', 't5_language_selector' );
add_action( 'save_post', 't5_save_language' );

function t5_language_selector()
{
    print '<div class="misc-pub-section">
        <label for="t5_language_id">Language</label>
        <select name="t5_language" id="t5_language_id">';

    $current = get_post_meta( get_the_ID(), '_language', TRUE );
    $languages = array (
        'en' => 'English',
        'de' => 'Deutsch',
        'ja' => '日本人'
    );

    foreach ( $languages as $key => $language )
        printf(
            '<option value="%1$s" %2$s>%3$s</option>',
            $key,
            selected( $key, $current, FALSE ),
            $language
        );

    print '</select></div>';
}


function t5_save_language( $id )
{
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
        return;

    if ( ! current_user_can( 'edit_post', $id ) )
        return;

    if ( ! isset ( $_POST['t5_language'] ) )
        return delete_post_meta( $id, '_language' );

    if ( ! in_array( $_POST['t5_language'], array ( 'en', 'de', 'ja' ) ) )
        return;

    update_post_meta( $id, '_language', $_POST['t5_language'] );
}

Leave a Comment

tech