2017-06-09 1 views
1

Dans WooCommerce, j'essaie d'ajouter un select qui affiche tous les produits. Je suis en utilisant le code suivant:WooCommerce - Ajouter des URLs de produits aux valeurs déroulantes

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);"> 

    <option value="">- Select Value - </option> 
    <?php 
     $args = array('post_type' => 'product'); 
     $loop = new WP_Query($args); 
     while ($loop->have_posts()) : 
      $loop->the_post(); 
      echo '<option value="#">'.the_title('','',false).'</option>'; 
     endwhile; 
    ?> 

</select> 

Cela fonctionne, mais je suis incapable de trouver un moyen d'ajouter aussi le lien du produit à la valeur de l'option.

J'ai essayé le code permalien standard et

$url = get_permalink($product_id); 

Mais cela ne fonctionne pas.

+0

où avez-vous eu $ product_id? à l'intérieur de votre boucle, il n'y a rien de tel. – Alice

Répondre

0

La réponse ici pour obtenir le Code produit est:

$product_id = $loop->post->ID; 

Ainsi, le code pour obtenir l'URL du produit pourrait être:

$product_id = $loop->post->ID; // Product ID 
$product = wc_get_product($product_id); // WC_Product object (instance) 
$product_link = $product->get_permalink(); 

Ou

$product_id = $loop->post->ID; // Product ID 
$product_link = get_permalink($product_id); 

Ainsi, votre dernière le code doit être:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);"> 

    <option value="">- Select Value - </option> 
    <?php 
     $args = array('post_type' => 'product'); 
     $loop = new WP_Query($args); 
     while ($loop->have_posts()) : 
      $loop->the_post(); 
      $post_id = $loop->post->ID; 
      $product = wc_get_product($post_id); 
      $link = get_permalink($post_id); 
      $title = $product->get_name(); 
      echo '<option value="'.$link.'">'.$title.'</option>'; 
     endwhile; 

     // Reset post data 
     wp_reset_postdata(); 
    ?> 

</select> 
+0

A travaillé parfaitement, merci beaucoup :-) – CharlyAnderson