/*

Theme Name: Pro &ndash; Child Theme
Theme URI: https://theme.co/pro/
Author: Themeco
Author URI: https://theme.co/
Description: Make all of your modifications to Pro in this child theme.
Version: 1.0.0
Template: pro

*/

function books_by_number_shortcode( $atts ) {

    $atts = shortcode_atts(
        array(
            'category' => '',   // product category slug
            'limit'    => -1,   // number of products
        ),
        $atts,
        'books_by_number'
    );

    if ( empty( $atts['category'] ) ) {
        return '<p>No product category specified.</p>';
    }

    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => intval( $atts['limit'] ),
        'tax_query'      => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => sanitize_text_field( $atts['category'] ),
            ),
        ),
        'meta_key'       => 'book_number',
        'orderby'        => 'meta_value_num',
        'order'          => 'ASC',
    );

    $query = new WP_Query( $args );

    if ( ! $query->have_posts() ) {
        return '<p>No products found.</p>';
    }

    ob_start();

    echo '<div class="books-by-number">';

    while ( $query->have_posts() ) {
        $query->the_post();
        global $product;

        $book_number = get_field( 'book_number' );

        echo '<div class="book-item">';
            echo '<a href="' . get_permalink() . '">';
                echo get_the_post_thumbnail( get_the_ID(), 'medium' );
                echo '<h3>' . get_the_title() . '</h3>';
                if ( $book_number !== '' ) {
                    echo '<span class="book-number">Book ' . esc_html( $book_number ) . '</span>';
                }
                echo '<span class="price">' . $product->get_price_html() . '</span>';
            echo '</a>';
        echo '</div>';
    }

    echo '</div>';

    wp_reset_postdata();

    return ob_get_clean();
}

add_shortcode( 'books_by_number', 'books_by_number_shortcode' );
