function product_dropdown_shortcode() { ob_start(); // Query to get all products $products = get_posts(array( 'post_type' => 'product', 'posts_per_page' => -1, )); // Output the dropdown HTML ?> <select id="product_dropdown"> <option value="">Select a product</option> <?php foreach ($products as $product) : ?> <option value="<?php echo esc_attr($product->ID); ?>"><?php echo esc_html($product->post_title); ?></option> <?php endforeach; ?> </select> <script> jQuery(function($) { // Initialize select2 for searchable dropdown $('#product_dropdown').select2(); }); </script> <?php return ob_get_clean(); } add_shortcode('product_dropdown', 'product_dropdown_shortcode'); function enqueue_select2() { // Enqueue Select2 library wp_enqueue_script('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.min.js', array('jquery'), '4.1.0-beta.1', true); wp_enqueue_style('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/css/select2.min.css', array(), '4.1.0-beta.1'); } add_action('wp_enqueue_scripts', 'enqueue_select2');
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter