Shane
Shane

Reputation: 87

Permalinks to admin-ajax.php

I am trying to use ajax to load new pages in my wordpress site, using wp_nav_menu and a permalink setup something like: /wp-admin/admin-ajax.php?post_name=%postname%/ to route the request to admin-ajax where I can handle it properly(according to the wordpress docs.) However wordpress just ignores my permalink and sticks with its default link setup.

Is this the right way to do this or would I be better of just rewriting the .htaccess file and would this cause problems updating to a new version of wp?

Thanks in advance for any answers.

Upvotes: 0

Views: 661

Answers (1)

Levi Putna
Levi Putna

Reputation: 3073

Chris at CSS Tricks has a great AJAX page load tutorial, the best bit about his solution os that it still work on older browsers that don't support JavaScript.

Script

<script type="text/javascript">
/*
 * Your navigation bar, can be "document" or body if you want to 
 * apply to every link on your site
*/
var $navigation = $("#site-menu");

//Your main content that will be replaces
var body = "#page-body";
var $body = $(body);

$navigation.delegate("a", "click", function() {
    window.location.hash = $(this).attr("href");
    return false;
});

$(window).bind('hashchange', function() {
    var newHash = window.location.hash.substring(1);
    if(newHash) {
        $body.fadeOut(200, function() {
            $body.hide().load(newHash + " " + body, function() {
                $body.fadeIn(200, function() {
                });
            });
        });
    };
});

$(window).trigger('hashchange');
</script>

Menu

Add your menu as you normaly would, make sure to add the site-menu id some tag that wraps the menu links that you want to ajax load.

<div id="site-menu">
    <?php wp_nav_menu(); ?>
</div>

Details

All the links under $navigation will have a click event added to them that will update the window url hash. The window is listening for the hash change and will use the hash value to make an AJAX request to reload the $body html.

Advantage

  • History (Back & Forward) navigation will work:
  • The same site will work with browsers that support JavaScript and browsers that don't;
  • If you copy past the url the script will load the correct page;
  • Because we are using the delegate function any links that are added via the result of the ajax load will also have the click event added to them

Disadvantage

  • You can no longer use anchors on your site

For more information and a example see: http://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/

Upvotes: 1

Related Questions