开发者

Wordpress AJAX Content

How can I load dynamic wp content into my wordpress blog index page?

Ideally I'd have the index page which sends GET requests with a ?tag= query, to another page开发者_如何学编程 which renders a list of posts that I want to see in my blog. How can I implement this?


You can get the rss version of the tag feed using the following url: http://[[domain_name]]/tag/[[tag_name]]/feed/

Replace [[domain_name]] with your domain name and [[tag_name]] with the tag you are looking for.

You can then parse this XML/RSS using javascript

hth


For me, I would do something like this:

  1. make tag-the_tag_slug.php (if you have it already, that's good)

  2. In the AJAX get request, send request to url http://yourdomain.com/the_tag_slug (or your tag's url, which would list out posts in the tag)

  3. send the request with one more $_GET params, such as $_GET["using_ajax"] = true

  4. in tag-the_tag_slug.php, if $_GET["using_ajax"] is false or undefined, do your normal html output. Otherwise, run through the loop and generate your desired HTML output.

  5. After the ajax call, in the success function, just insert the returned HTML output to the place you want.

Reason to do this, is that in WP 3.0, you have a template tag called get_template_part(), so your ajaxified loop output could be extracted out to like loop-ajax_tag.php. And in theory, you could add as many as you want (and choose the one by determining such as $_GET["loop-template"])

Another reason is you don't need many javascript DOM creation or modification (returning xml / json requires you interpret those data in jaavscript, and you properly have to copy and paste a lot template codes into javascript)


I have an easier solution using the standard AJAX WordPress guidelines. In your functions.php add the following code:

add_action('wp_ajax_posts_by_tag', 'ajax_posts_by_tag');
add_action('wp_ajax_nopriv_posts_by_tag', 'ajax_posts_by_tag');

function ajax_posts_by_tag() {
  $q = new WP_Query('tag=' . $_POST['tag'])
  echo '<ul>';
  while ($q->have_posts())
  {
    $q->the_post();
    echo '<li>' . $q->post->post_title . '</li>';
  }
  echo '</ul>';

  die();
}

Then, inside your javascript on your homepage, use the following method to retrieve the contents by tag (assuming you're using jQuery):

jQuery(document).ready(function($) {
  var data = {
    action: 'posts_by_tag',
    tag: 'my-tag'
  };

  jQuery.post(ajaxurl, data, function(response) {
    alert(response);
  });
});

Something like that. You can then squeeze the response into any block on the page. This will fetch for posts tagged my-tag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜