jQuery 通过 ajax 加载 Wordpress 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26941256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:27:12  来源:igfitidea点击:

jQuery load Wordpress pages via ajax

ajaxwordpress

提问by davidcondrey

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

我正在尝试设置一个 Wordpress 主题,它使用 AJAX 加载页面(而不是帖子)。我正在遵循本指南,但无法加载正确的页面。

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

帖子的链接是用 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..

URL 是正确的,但它不加载任何东西..



<?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; ?>

回答by davidcondrey

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

第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 文件来完成,该文件具有类似于以下的注释标题:

<?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.

出于语义目的,我将其命名为 Ajax,但在教程中,原作者将其命名为“Triqui Ajax”。记下您创建的 PHP 文件的名称,因为稍后您将在步骤 4 中再次使用它。

Step 2

第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)

完成后,您可以继续编写自定义页面模板,除了添加下面的注释行(第 2 行到第 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

第 3 步

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

创建自定义页面模板后,您现在应该登录 wp-admin 并首先转到Settings -> Permalinks并将其设置为Day and NameCustom Structure。结构应如下所示:

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

Whether you write that manually in Custom Structureor select Day Nameit should look like the above snippet.

无论您是手动编写Custom Structure还是选择Day Name它,都应该类似于上面的代码片段。

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.

现在去创建一个新页面。 Pages ->添加新'并创建一个新页面。随意命名,但最好将其命名为您在步骤 1 中创建的页面模板的名称。

Save it as an empty page. NOW THIS IS THE IMPORTANT PARTYou 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.

将其另存为空页。 现在这是重要的部分您需要确保页面的永久链接与您在步骤 1 中创建的文件具有完全相同的名称。唯一的区别是它应该全部小写。

Step 5

第 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.

您现在应该有一个 PHP 文件。以及 WP-admin 中的一个页面。该页面应该有一个与 PHP 文件的文件名(全部小写)匹配的永久链接 URL,并且应该为该页面分配该文件的页面模板。

This page should remain empty and should never be used.

此页面应保持为空,不应使用。

Step 6

第 6 步

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

header.php代码之后立即<?php wp_head() ?>添加以下脚本:

<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.

将 THELINK 替换为您放置<?php the_permalink ?>代码的元素。

The only lines that you need to change are lines 5 and 12. Notice on line 12 where it is written ajaxthis 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.

唯一需要更改的行是第 5 行和第 12 行。 请注意,在第 12 行中,这是ajax我在第 1 步中创建的 PHP 文件的名称和我在第 5 步中创建的页面的永久链接的名称。

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

同样在该行开头的第 12 行,您应该更改TARGET为应加载内容的元素。

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

确保在此脚本之前已正确加载 jQuery。

Step 7

第 7 步

Moving on to your index.phpfile or whichever file your loop is in. Find where-ever you have the code the_permalinkwhich 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:

转到您的index.php文件或您的循环所在的任何文件。找到the_permalink将位于锚标记上的代码的任何位置。您将需要添加一个 rel 属性,在第 6 步中的第 12 行使用the_ID()该属性{id:post_id}

<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.

就是这样。它现在应该可以工作了。页面应该使用 AJAX 加载,浏览器的 URL 也会更改以匹配。

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.

您现在可以根据自己的需要创建任意数量的页面,创建其他自定义页面模板,并根据需要分配它们。只要让您在第 5 步中创建的文件永远作为一个空页面存在即可。

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.

如果它仍然不起作用,您可能会绝望地迷失并且不知道自己在做什么。您很可能已经创建了某种 jQuery 冲突或没有正确加载 jQuery。

回答by Sree

Please check this link Load posts to div using ajax and jQueryor you can use this plugin Advanced AJAX Page Loader.

请检查此链接使用 ajax 和 jQuery帖子加载到 div,或者您可以使用此插件Advanced AJAX Page Loader

回答by Kidkie

I got an error saying

我有一个错误说

Notice: Use of undefined constant HTTP_HOST - assumed 'HTTP_HOST' in /var/www/***/public_html/wp-content/themes/*****/header.phpon line XX.

注意:使用未定义的常量 HTTP_HOST -在第 XX 行的/var/www/***/public_html/wp-content/themes/*****/header.php 中假定为“HTTP_HOST” 。

Fixed by adding single quotes around HTTP_HOSTin:

通过HTTP_HOST在以下位置添加单引号来修复:

$("#TARGET").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/ajax/",{id:post_id});