WPML Get url without outputting

I am in the process of migrating from qTranslate to WPML to handle my languages.

With qTranslate, I had a very simple way to get an url to a page or post knowing it’s slug: $url = get_language_url(home_url($slug));

Read More

Now with WPML I can’t find a way to do that…

There’s the icl_link_to_element function but it directly outputs the link in a a tag.. Besides, you need to know the post ID.

Any way I can get a link to a post in the correct language, knowing it’s slug?

Related posts

2 comments

  1. Actually WordPress lacks a real function to get posts by slug/post-name. But you can use get_page_by_path() for it so you don’t have to use a custom query:

    if(function_exists('icl_object_id')) {
       $post = get_page_by_path('your-slug');
       $id = icl_object_id($post->ID,'post',true);
       $link = get_permalink($id);
    }
    

    The only difference here is that you must use the full path i.e. ('parent-page/sub-page') if you have a hierarchical structure. For posts and non-hierarchical pages you can just use the slug as param.

  2. You can get link to a post by it’s slug using following code.

    <?php
    global $wpdb;
    $id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = 'name-of-slug'");
        if(function_exists('icl_object_id')){
            get_permalink(icl_object_id($id,'post',true)); 
        }
    ?>
    

Comments are closed.