简体   繁体   中英

Display with a shortcode a dropdown of Woocommerce products for a specific category

i want to display product by category with dropdown

and i made this code but why the value not going inside the ?

function rakitpc() {
    $args = array(
    'posts_per_page' => -1,
    'product_cat' => 'Tshirts',
    'hide_empty' => 0,
    'post_status' => 'publish',
    'post_type' => 'product',
    'orderby' => 'title',
    'echo' => '0'
    );
    $products = new WP_Query( $args );
    $output = '<select>';
    // foreach ( $products as $product ) {
    while ( $products->have_posts() ) {
        $products->the_post();
        $aa = the_permalink($post);
        echo $aa;
        $bb = the_title($post);
        $output .= "<option value=\"<?php the_permalink(); ?>\"> <?php the_permalink(); ?></option>";  
    }
    wp_reset_query();
    $output .='</select>';
    return $output;
    }
add_shortcode( 'gege', 'rakitpc' );

This is the output That I get:

输出

My reference: How do I display a "category products drop down in a wordpress page" in Woocommerce 2.5.2

Try the following that will give you a dropdown with the permalinks as <option> values displaying the product names (see the screenshot at the end) .

You will need to set your category name (or categories names) in the array inside the funtion.

function rakitpc() {
    // HERE below, define your Product category names
    $term_names = array('T-shirts');

    // The WP_Query
    $query = new WP_Query( array(
        'posts_per_page' => -1,
        'post_type' => 'product',
        'post_status' => 'publish',
        'hide_empty' => 0,
        'orderby' => 'title',
        'tax_query' => array( array(
            'taxonomy' => 'product_cat', // for a Product category (or 'product_tag' for a Product tag)
            'field'    => 'name',        // can be 'name', 'slug' or 'term_id'
            'terms'    => $term_names,
        ) ),
        'echo' => '0'
    ) );

    $output = '<select>';
    // foreach ( $products as $product ) {
    if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();

        $permalink = get_permalink($query->post->ID);
        $title = $query->post->post_title;
        $output .= '<option value="' . $permalink . '">' . $title . '</option>';

    endwhile;

    wp_reset_postdata();

    $output .='</select>';

    else :

    $output = '<p>No products found<p>';

    endif;

    return $output;
}

add_shortcode( 'gege', 'rakitpc' );

Code goes in function.php file of your active child theme (or active theme). Tested and works.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM