Get the grouped product link from one of it's childs in woocommerce 3

最后都变了- 提交于 2019-12-04 18:47:00

It's possible to build that function for WooCommerce 3+ this way:
(with an optional $post_id argument)

/**
 * Get a button linked to the parent grouped product.
 *
 * @param string (optional): The children product ID (of a grouped product)
 * @output button html
 */
function parent_permalink_button( $post_id = 0 ){
    global $post, $wpdb;

    if( $post_id == 0 )
        $post_id = $post->ID;

    $parent_grouped_id = 0;

    // The SQL query
    $results = $wpdb->get_results( "
        SELECT pm.meta_value as child_ids, pm.post_id
        FROM {$wpdb->prefix}postmeta as pm
        INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
        INNER JOIN {$wpdb->prefix}term_relationships as tr ON pm.post_id = tr.object_id
        INNER JOIN {$wpdb->prefix}terms as t ON tr.term_taxonomy_id = t.term_id
        WHERE p.post_type LIKE 'product'
        AND p.post_status LIKE 'publish'
        AND t.slug LIKE 'grouped'
        AND pm.meta_key LIKE '_children'
        ORDER BY p.ID
    " );

    // Retreiving the parent grouped product ID
    foreach( $results as $result ){
        foreach( maybe_unserialize( $result->child_ids ) as $child_id )
            if( $child_id == $post_id ){
                $parent_grouped_id = $result->post_id;
                break;
            }
        if( $parent_grouped_id != 0 ) break;
    }
    if( $parent_grouped_id != 0 ){
        echo '<a class="button" href="'.get_permalink( $parent_grouped_id ).'">Link to Parent</a>';
    } 
    // Optional empty button link when no grouped parent is found
    else {
        echo '<a class="button" style="color:grey">No Parent found</a>';
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works in WooCommerce 3+


USAGE: (2 cases)

1) Without using the optional argument $post_id for example directly in the product templates:

parent_permalink_button();

2) Using the function everywhere, defining the it's argument $post_id:

$product_id = 37; // the product ID is defined here or dynamically…
parent_permalink_button( $product_id );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!