Skip to content
Advertisement

Woocommerce $product class can’t be accessed inside PHP snippet

I’m trying to write a PHP code for showing extra fields on my product page with “Woody Snippets” in WordPress. But I can’t access the $product class inside my snippet. Is it not possible or am I doing something wrong?

Here is my code:

    global $product;

    $seller = get_post_field( 'post_author', $product->get_id());
    $author  = get_user_by( 'id', $seller );
    $store_info = dokan_get_store_info( $author->ID );

    ?>
        <span class="details">
            <?php printf('Call me at <a href="tel:%s">%s</a>', $store_info['phone'], $store_info['phone']) ?>
        </span>

Advertisement

Answer

I realized the cause of the problem is my theme. My theme uses templates for viewing posts like posts, products, store pages, etc. And because of that, woocommerce product page ID points to the template’s ID, and there is no accessible $product class on that page. So I found the solution by querying, like the following.

global $wp;
global $wp_query;

$productid = url_to_postid(home_url( $wp->request));
$postdata = get_postdata($productid);

$authorID = $postdata['Author_ID'];

$store_info = dokan_get_store_info( $authorID );
?>
    <span class="details">
        <?php printf('<a href="tel:%s">%s</a>', 
            $store_info['phone'], $store_info['phone']) ?>
    </span>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement