I want to load products deatails on my custom page.Is there any way that i can use the url key like http://localhost/mysite/product/samsung-1.In this url samsung-1 is the key for that product.I want to use this and get product details like name,description and attributes.Can i do this using url key or i have to use id for this.thanks I tried this code but this uses id :

<?php $post = get_post('5653'); //assuming $id has been initialized
echo "<pre/>";

2 Answers 2


You simply can use the existing function get_page_by_path() for this, which has a third parameter $post_type you can specify. In your case a post from the custom post type product is what you want.

Basic example:

$product_obj = get_page_by_path( $slug, OBJECT, 'product' );

You can use following function

* Retrieve a product given its slug.

function get_product_by_slug($page_slug, $output = OBJECT) {
    global $wpdb;
        $product = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, 'product'));
        if ( $product )
            return get_post($product, $output);

    return null;


$product = get_product_by_slug('samsung-1');

Its not tested though

  • Thanks great it working.but how can i get product attributes like i added camera->5px its not showing on details ? Oct 28, 2015 at 15:39
  • Attributes need to be received additionally, e.g. with wc_get_product_terms(). @MahmoodRehman Oct 28, 2015 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.