Get the grouped product link from one of it's

2019-05-29 19:48发布

With woocommerce 2.3 there was post_parent for single products what was the part of grouped product. So it was possible to link them by:

function parent_permalink_button() {
   global $post; 
   if( $post->post_parent != 0 ){ 
       $permalink = get_permalink($post->post_parent);
       echo '<a class="button" href="'.$permalink.'">Link to Parent</a>';
   }
}

with woocommerce 3.0.0 update situation changed. Actually it is opposite now. Grouped product has its _children.

How can I create the link from single product to its grouped? It can be a part of more grouped product so there can be multiple links (but it is not the case of my shop)

Thanks Michal

1条回答
狗以群分
2楼-- · 2019-05-29 20:41

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 );
查看更多
登录 后发表回答