tags:

views:

15

answers:

3

I'd like to implement a custom post retrieval page in wordpress. Basically, I'm using AJAX to call this page that will be passed a post ID and retrieve certain data from that post.

Note: please don't mistake this as a template question. I do not want a template for one single page -- I am looking to make this page query multiple different posts based on postID and return certain data from that post.

So I tried creating a page

<?php
$args=array(
       'p'=>'77'
    );
    $friends = new WP_Query($args);
?>
<?php if ($friends->have_posts()) : the_post(); ?>

    <?php the_title(); ?>
    <?php the_content(); ?>

<?php else: ?>
    <p>Sorry, no posts are available.</p>
<?php endif; ?>

But this does not work since it is not loading in the wp functions to handle the query.

Thanks in advance for any help!

A: 

sorry have to use templates i guess

sharon
+1  A: 

You have to include the wp-blog-header.php file. If the page you are creating is in your theme's folder then you would put something like this at the top of your code

<?php require_once ('../../../wp-blog-header.php');?>

aaronwaggs
+1  A: 

I think I guess what you are trying to do, and it sounds like you are going about it the wrong way. Do not make a 'new page' in the admin interface. What you want to do is serve up a file (JSON, XHTML fragment, whatever) to your Javascript and include in it WP data, right? I know that problem, having used it in some of my plugins.

There are two techniques:

(1) This is what you need to do: make a new plugin (just a loose php file in wp-plugins with the same format header as the other plugins in there). Write your function along these lines:

function mydatapage(){
    if (...$_SERVER['REQUEST_URI'] == the one I am using ...) {
        $args=array(
            'p'=>'77'
        );
        $friends = new WP_Query($args);
        if ($friends->have_posts()) :
            the_post();
            the_title();
            the_content();
        else:>?
<p>Sorry, no posts are available.</p>
        <?php endif;
        die();
    } //else do nothing and leave WP to serve the page normally
}
//Crucially:
add_action('init', 'mydatapage');

What that does is do a lookup when pages are loaded to see if the url matches the one you want to hijack and use to send your custom data. If it is, you send the data/file/whatever you feel like and exit (die).

Give a shout if you want more detailed syntax. It is a bit messy, but works well.

(2) Directly call your plugin file. WP will only handle files that do not already exist, and leave the rest to Apache. That means you can make a plugin file and call that directly using the .../wp-plugin/myfile.php url. You would need to include some of the WP core files to get things like WP_Query to work. It is marginally more fragile a method.

Nicholas Wilson