Search code examples
phpwordpresswoocommerceshortcodewordpress-shortcode

Wordpress/WooCommerce Shortcode for min. age


I could need some help creating a Shortcode for Wordpress/Woocommerce since PHP isn't really my strength.

I want to display the minimum age for a product on its product page.

Therefore I should use these values:

$gzd_product = wc_gzd_get_gzd_product( $product );
$min_age = $gzd_product->get_min_age();

Based on this file: https://github.com/vendidero/woocommerce-germanized/blob/master/includes/abstracts/abstract-wc-gzd-product.php#L268

I guess this should be an easy task if you know what you're doing, but I've never created a shortcode on my own and the tutorials I can find feel a little too basic for this task. I mean I probably have to add a "this"-rule somewhere so it knows to take the value of the current product...?

Anyways, thanks a lot if someone could help!


Solution

  • You're on the right lines, but what you need to do is put your code within the single-products.php, usually a theme calls content-single-product.php (I would start there)

    It really depends where on the product page you want this, but you could put it at the end of the summary? (Whether the title and price etc is)

    Locate the content-single-product.php and find this

        <div class="summary entry-summary">
        <?php
        /**
         * Hook: woocommerce_single_product_summary.
         *
         * @hooked woocommerce_template_single_title - 5
         * @hooked woocommerce_template_single_rating - 10
         * @hooked woocommerce_template_single_price - 10
         * @hooked woocommerce_template_single_excerpt - 20
         * @hooked woocommerce_template_single_add_to_cart - 30
         * @hooked woocommerce_template_single_meta - 40
         * @hooked woocommerce_template_single_sharing - 50
         * @hooked WC_Structured_Data::generate_product_data() - 60
         */
        do_action( 'woocommerce_single_product_summary' );
        ?>
    </div>
    

    Then you can copy your snippet before the ?>

    However if you go to Woocommerce templates folder and then the single product folder, you should see lots of template sections which you can also put your code inside of (depending where on the product page you want it.

    EDIT:

    To shortcode you would do something like (put in your function.php)

    // Add Shortcode
    function minage_shortcode() {
    global $product;
    
    $minage = get_post_meta( $product->get_id(), 'myfield', true );
    
    echo $minage
    }
    add_shortcode( 'minage', 'minage_shortcode' );
    

    Replace myfield with your custom field name

    this will give you [minage] as your shortcode