Search code examples
wordpressclassfiltertitlewpml

Get the title of the original page in your default language and add it as body class to the translated page on WordPress with WPML


Here's my problem:

add_filter( 'body_class', 'wpml_body_class');
function wpml_body_class( $class ) {
    global $sitepress, $post;

    if( $sitepress->get_default_language() != ICL_LANGUAGE_CODE ) {
        $original_id = icl_object_id( $post->ID, get_post_type(), true, $sitepress->get_default_language() );
        $class[] = strtolower(get_the_title( $original_id ));
    }

    return $class;
}

This code works fine. Essentially, I use $sitepress as a global to get my default language and then I extract the ID to match it with get_the_title, so, at the end of the day, I added the title as a class name to the body, so I can easily replicate the style of the original page without adding a line on my CSS stylesheet file on the translated page, in this case in French.

So far so good, except for a caveat:

Since this is the title, if I have a title like Our Team, I have to add a dash to the style, and it is going to change base on how many words I have. If I have to use the URL instead, the process to extract it with WordPress is more complex, so I was wondering if it is possible to add a regular expression to add a dash if I have any space. Or if everyone else knows how to extract the URL instead of get_the_title I couldn't be more grateful.


Solution

  • what you need is sanitize_title_with_dashes() for your purpose :) which is provided by WP . Reference https://codex.wordpress.org/Function_Reference/sanitize_title_with_dashes