一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

wordpress中AJAX随机取一条记录的例子

时间:2014-03-17 编辑:简简单单 来源:一聚教程网

点击“换一个”随机换一条内容。

由于有“标准”“图像”“视频”等文章形式,这里换一个需要随机获取一篇文章形式是图像的文章,并且把图片,和链接取出,使用ajax替换内容。

①我们可以建立一个新页面模板,模板名字就叫做recommend

新建页面模板:

/*
 * Template Name:换一条
 */
然后在后台管理新建一个页面,选择这个模板,取名recommend,这样就建了一个新页面

②在模板中取得并输出需要替换的内容

 代码如下 复制代码
/*
 * Template Name:换一条
 */ www.111com.net
$args = array(
  'tax_query' => array(
    array(
      'showposts' => '1',
      'taxonomy' => 'post_format',
      'field' => 'slug',
      'terms' => 'post-format-image',
    )
  ),
  'orderby'=>'rand',
);
query_posts($args);
the_post();
?>

这是随机找出一篇文章形式为图像的文章。

 代码如下 复制代码

 catch
_that_image();?>
 叫人起床的N种奇葩方式
 

这里就是需要显示的html,我们把链接和图片地址都替换了。

catch_that_image函数:

 代码如下 复制代码
function catch_that_image() {
 global $post, $posts;
 $first_img = '';
 ob_start();
 ob_end_clean();
 $output = preg_match_all('//i', $post->post_content, $matches);
 $first_img = $matches [1] [0];
 
 // no image found display default image instead
 if(empty($first_img)){
  $first_img = "/images/default.jpg";
 }
 return $first_img;
}
?>

这个函数可以取出改篇文章的第一篇图片。

③在前端页面写上ajax函数

 代码如下 复制代码
   
 
   

这样,这个“换一个”ajax效果就做好了。

热门栏目