如何在 WordPress 中使用 ajax 调用短代码来显示 Elementor 模板?

问题描述 投票:0回答:1

我想使用ajax调用短代码来显示Elementor模板。模板短代码是:[elementor-template id="1008"]

这是我正在尝试使用的 Ajax:

jQuery.ajax({
        type: 'POST',
        url : 'https://somedomain.com.au/wp-admin/admin-ajax.php',
        cache: false,
        data : { 'action': 'elementor-template', 'id': '1008' },
        complete : function() {  },
        success: console.log(data),
        error: console.log(error)
    });
ajax wordpress shortcode
1个回答
0
投票
To use AJAX in WordPress to call a shortcode that displays an Elementor template, you need to follow a specific approach.

-- Go to the theme's "functions.php" and add the following code.

function my_ajax_function() {
    $template_id = isset($_POST['id']) ? $_POST['id'] : '';
    $shortcode = '[elementor-template id="' . esc_attr($template_id) . '"]';
    
    echo do_shortcode($shortcode);

    wp_die(); // This is required to terminate immediately and return a proper response
}

add_action('wp_ajax_elementor_template', 'my_ajax_function');
add_action('wp_ajax_nopriv_elementor_template', 'my_ajax_function'); // If you want to allow non-logged-in users

Update your AJAX script to match the AJAX action you just created:

jQuery.ajax({
    type: 'POST',
    url: ajaxurl, // WordPress AJAX URL
    data: {
        'action': 'elementor_template', // This should match the wp_ajax_ action hook
        'id': '1008'
    },
    success: function(data) {
        console.log(data); // Output the result in the console
        // Use the data to update your page as needed
    },
    error: function(error) {
        console.log(error);
    }
});

With these changes, your AJAX request should correctly trigger the WordPress AJAX action you defined,

Thanks,
Mick
© www.soinside.com 2019 - 2024. All rights reserved.