horizontal menu with ajax call

WPTurbo » Snippets » horizontal menu with ajax call
0

Created with:

Visibility: 

public

Creator: Lauren

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

namespace WPTurbo;

function wpturbo_render_horizontal_menu() {
    ob_start();
    ?>
    <div class="horizontal-menu-container">
        <button class="scroll-left">&lt;</button>
        <div class="horizontal-menu">
            <ul>
                <?php for ($i = 1; $i <= 20; $i++): ?>
                    <li data-item="<?php echo $i; ?>" class="menu-item">Item <?php echo $i; ?></li>
                <?php endfor; ?>
            </ul>
        </div>
        <button class="scroll-right">&gt;</button>
    </div>
    <div class="content-display">
        <p>Select a menu item to see the content here.</p>
    </div>
    <?php
    return ob_get_clean();
}

add_shortcode( 'horizontal_menu', 'WPTurbowpturbo_render_horizontal_menu' );

function wpturbo_handle_ajax_request() {
    // Check if the necessary GET parameter is present
    if ( isset( $_POST['item'] ) ) {
        $item = intval( $_POST['item'] ); // Sanitize the input
        // Example script logic based on the item value
        $output = "You selected Item " . $item . ". Here is your dynamic content.";

        // Return the response
        wp_send_json_success( $output );
    } else {
        wp_send_json_error( 'No item specified' );
    }
}

// Hook for logged-in users
add_action( 'wp_ajax_wpturbo_get_content', 'WPTurbowpturbo_handle_ajax_request' );

// Hook for non-logged-in users
add_action( 'wp_ajax_nopriv_wpturbo_get_content', 'WPTurbowpturbo_handle_ajax_request' );

function wpturbo_enqueue_scripts() {
    wp_enqueue_script( 'wpturbo-menu-script', plugin_dir_url( __FILE__ ) . 'js/menu-script.js', ['jquery'], null, true );
    wp_localize_script( 'wpturbo-menu-script', 'wpturbo_ajax', [
        'ajax_url' => admin_url( 'admin-ajax.php' )
    ]);
}

add_action( 'wp_enqueue_scripts', 'WPTurbowpturbo_enqueue_scripts' );
				

With these changes, clicking on a menu item will execute the PHP script on the server, passing the relevant value, and dynamically update the content displayed in the div without navigating away from the page.

Make sure to save all changes and test the functionality in your WordPress environment.

Register an account to save your snippets or go Pro to get more features.