For a project, i've to improve SEO perf and one of this optimization is to load the sidebar with an ajax request.

I've looking for this solution through the documentation, source code, plugins repository without success.

So i need your help and advices. Is it possible to do this ? If yes, what is the best way ?



I didn't test anything, but I imagine it would be something like this:

As you must include a sidebar.php, just include an empty sidebar.php, and leave the real one to the sidebar-ajax.php, for example.

To call the sidebar:

<?php get_template_part('sidebar'); ?>

And it should be something like this:

<div id="sidebar"></div>

In your functions.php:

add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
function theme_enqueue_scripts() {
    /* load your js file in footer */
    wp_enqueue_script('theme-script', get_stylesheet_directory_uri() . '/your-js-file.js', false, false, true);

add_action('wp_ajax_get_ajax_sidebar', 'check_ajax');
add_action('wp_ajax_nopriv_get_ajax_sidebar', 'check_ajax');
function check_ajax() {

And in your-js-file.js:

    type: 'POST',
    url: location.href,
    data: { get_ajax_sidebar: 1 },
    success: function(data){
  • Sorry for belayted answer but your solution works fine. Thanks a lot. – ptiswitz Oct 17 '12 at 9:48
  • Error #1: get_template_part('sidebar-ajax'); is outside of php tags! It will never work! Error #2: location.href will actually call loaded page itself and inject into the sidebar content, instead a proper path to the template file must be specified. – dev101 Dec 23 '18 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.