简体   繁体   English

我想在一个单独的php文件上运行wp_query以进行a​​jax调用

[英]I want to run wp_query on a separate php file for an ajax call

For example: 例如:

<?php $numposts = $_POST['showposts']; ?>


<?php $home_query_bottom = new WP_Query("cat=&showposts=$num_posts&offset=5"); $b = 0; ?>
<ul class="thumbs">
    <?php while ($home_query_bottom->have_posts()) : $home_query_bottom->the_post();
        $do_not_duplicate = $post->ID; $b++; ?>

        <li class="post-<?php the_ID(); ?> thumb"><?php get_the_image( array( 'custom_key' => array( 'thumbnail' ), 'default_size' => 'thumbnail', 'width' => '160', 'height' => '160' ) ); ?></li>
    <?php endwhile; wp_reset_query(); $b = 0; ?>
</ul>

The code above is on its own php file ready to be called by the main wordpress page, however I get an error saying wp_query class not found. 上面的代码是在自己的php文件中准备好由主wordpress页面调用,但是我得到一个错误,说找不到wp_query类。 I'm assuming it's because I am not using the header.html which probably has a bunch of includes. 我假设它是因为我没有使用header.html,它可能有一堆包含。 What do I need for that page to utilize the wp_query class? 该页面使用wp_query类需要什么?

您可以关闭模​​板引擎,然后包含标题。
// Include WordPress
define('WP_USE_THEMES', false);
require_once('PATHHERE/wp-blog-header.php');

You have to include the file that has the Wordpress functions located on the main directory of the Wordpress Installation: 您必须包含Wordpress功能位于Wordpress安装主目录中的文件:

define('WP_USE_THEMES', false);  
require_once('../../../wp-load.php');

../../../ = path to the main directory on your installation ../../../ =安装主目录的路径

I found a nice tutorial about this here . 我在这里找到了一个很好的教程。

You have to make the page that ajax calls a template page. 您必须创建ajax调用模板页面的页面。 Make a new page in your blog and assign the template. 在博客中创建一个新页面并分配模板。 no headers no includes. 没有标题不包含。

This worked for me, maybe it will help someone else. 这对我有用,也许它会帮助别人。

My situation is I have a js file that uses getScript. 我的情况是我有一个使用getScript的js文件。 In that script i have a bunch of .load() calls to a php file. 在那个脚本中,我有一堆.load()调用一个php文件。 At the top I place this. 在顶部我放置这个。

if (file_exists("../../../wp-load.php"))
    {
    require_once("../../../wp-load.php");
    }

Change the ../ to how ever many directories your wp-load file is up. ../更改为wp-load文件启动的目录。

Edit - Using WP 3.4.1 编辑 - 使用WP 3.4.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM