Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery load Wordpress pages via ajax

Tags:

ajax

wordpress

I'm trying to setup a Wordpress theme which loads pages (not posts) with AJAX. I was following this guide but haven't been able to get the correct pages to load.

The links to the posts are being generated with the post slug

http://local.example.com/slug/

So I adjusted

 jQuery(document).ready(function($){
        $.ajaxSetup({cache:false});
        $("a.bar").click(function(e){
            $('page-loader').show();
            var that = $(this).parent();

            $('.column').not($(this).parent()).animate({width: 'toggle',opacity:'0.75'}, 700, function() {

            });

            var post_id = $(this).attr("href");
            $("#page-container").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>" + post_id,{id:post_id});

            return false;
        });
    });

The URL is correct but it doesn't load anything..


<?php
/*
Template Name: Triqui Ajax Post
*/
?>
<?php
$post = get_post($_POST['id']);
?>
<?php if ($post) : ?>
    <?php setup_postdata($post); ?>
    <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
        <h2><?php the_title(); ?></h2>
        <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

        <div class="entry">
            <?php the_content('Read the rest of this entry &raquo;'); ?>
        </div>

    </div>
<?php endif; ?>
like image 752
davidcondrey Avatar asked Nov 15 '14 00:11

davidcondrey


1 Answers

So I was actually able to get this working by following the tutorial I mentioned previously; I think the tutorial may have just been written a bit unclearly..

Step 1

Create a custom page template which is done by creating a PHP file in the root directory with a comment header similar to this:

<?php
/*
Template Name: Ajax
*/
?>

I titled it Ajax for the purpose of semantics, but in the tutorial the original author titled it 'Triqui Ajax'. Keep note of the name of the PHP file you create as you'll use it again later in Step 4.

Step 2

Once that's done, you can continue coding your custom page template with the exception of adding the annotated lines below (lines 2 thru 5)

<?php
    $post = get_post($_POST['id']); // this line is used to define the {id:post_id} which you will see in another snippet further down

    if ($post) { // this is necessary and is a replacement of the typical `if (have_posts())`
        setup_postdata($post); // needed to format custom query results for template tags ?>
        <!-- everything below this line is your typical page template coding -->
        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">

            <h2><?php the_title(); ?></h2>
            <small><?php the_time('F jS, Y') ?></small>
            <span><?php the_author() ?></span>

            <div class="entry">
                <?php the_content(); ?>
            </div>

        </div>

<?php }

Step 3

Once you've created your custom page template you should now login to the wp-admin and first, go to Settings -> Permalinks and set it to Day and Name or Custom Structure. The structure should look like this:

/%year%/%monthnum%/%day%/%postname%/

Whether you write that manually in Custom Structure or select Day Name it should look like the above snippet.

Step 4

Now go to create a new page. Pages ->Add New' and create a new page. Name it whatever you like, but it would be best to name it the same as the name of the page template you created in step 1.

Save it as an empty page. NOW THIS IS THE IMPORTANT PART You need to make sure that the permalink of the page has the exact same name as the file you created in Step 1. Only difference is it should be all lowercase.

Step 5

Before you save the page, also make sure you select the page template, from the select menu. If you do not see this menu it is because you probably did not create the template file correctly, or you did not create it in the root directory, or you did not create the comment header properly. Basically, the menu does not show if you do not have any custom page templates created, it only shows if it seems a proper custom page template saved in the root directory of your theme.

enter image description here

Review

You should now have a PHP file. And a page in the WP-admin. The page should have a permalink URL which matches the filename of the PHP file (all lowercase) and the page should be assigned the page template of that file.

This page should remain empty and should never be used.

Step 6

In header.php immediately following the code <?php wp_head() ?> add the following script:

<script>

    jQuery(document).ready(function($){
        $.ajaxSetup({cache:false});
        $("THELINK").click(function(e){ // line 5
            pageurl = $(this).attr('href');
            if(pageurl!=window.location) {
                window.history.pushState({path: pageurl}, '', pageurl);
            }

            var post_id = $(this).attr("rel")
            $("#TARGET").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/ajax/",{id:post_id}); // line 12
            return false;
        });
    });
</script>

Replace THELINK with the element where you have placed the <?php the_permalink ?> code.

The only lines that you need to change are lines 5 and 12. Notice on line 12 where it is written ajax this is the name of the PHP file I created in step 1 and the name of the permalink of the page I created in step 5.

Also on line 12 at the beginning of that line, you should change TARGET to the element in which the content should be loaded.

Make sure you've properly loaded jQuery before this script.

Step 7

Moving on to your index.php file or whichever file your loop is in. Find where-ever you have the code the_permalink which will be on an anchor tag. You will need to add a rel attribute with the_ID() which is used by {id:post_id} on line 12 in step 6:

<a href="<?php the_permalink(); ?>" class="bar" rel="<?php the_ID(); ?>" title="<?php the_title(); ?>">

Done

That's it. It should now work. The pages should be loaded with AJAX, and the URL of the browser will also change to match.

You can now go about creating as many pages as your hearts desire, creating other custom page templates, and assigning them, whatever you like.. Just let that file you created in Step 5 live where it is as an empty page forever.

If it still does not work, you are probably hopelessly lost and have no idea what your doing. You most likely have created some sort of jQuery conflict or have not loaded jQuery properly.

like image 91
davidcondrey Avatar answered Oct 06 '22 05:10

davidcondrey