动态筛选字preSS职位与下拉菜单(使用PHP和AJAX) [英] Dynamically filter Wordpress posts with dropdown menu (using php and ajax)

查看:202
本文介绍了动态筛选字preSS职位与下拉菜单(使用PHP和AJAX)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:我想作一个动态的页面,让访问者从下拉菜单中选择月份和年份,有根据所选择的这些值的页面改变的内容(职位)

Goal: I would like to make a dynamic page that allows the visitor to select a month and year from a drop-down menu and have the content (the posts) on the page change according the the values selected.

我目前使用下面的code,从一个特定的月份和年份显示来自一个特定类别的帖子。

I'm currently using the following code to display posts from a particular category from a particular month and year.

<?php query_posts("cat=3&monthnum=12&year=2011"); ?> <?php if (have_posts()) : ?>
     <ul>
    <?php while (have_posts()) : the_post(); ?>
        <li>
           <?php the_title(); ?>
           <?php the_excerpt(); ?>
        </li>
    <?php endwhile; ?>
     </ul><?php endif; ?>

它运作良好,但我想使页面动态,这样游客可以从下拉菜单中选择一个年份和月份,并有根据所选的值含量的变化。我已经发布了它如何在这里工作的照片:fivepotato.com/images/ex1.png~~V 和fivepotato.com/images/ex2.png~~V。

It works well, but I would like to make the page dynamic so that the visitor can select a month and year from a drop-down menu and have the content change according the the values selected. I've posted pictures of how it would work here: fivepotato.com/images/ex1.png and fivepotato.com/images/ex2.png.

为使这项工作,我知道我将不得不作出monthnum一个变量的值(这是从下拉列表:

To make this work, I know that I will have to make the value of monthnum a variable (which is taken from the dropdown list:

<?php $monthvar = $_POST["month"]; query_posts("cat=3&monthnum=$monthvar&year=2011");?>

我没有与阿贾克斯太多的经验,但我认为我需要用它做每月一次从下拉菜单中选择的内容重新过滤。

I don't have much experience with Ajax, but I assume that I will need to use it to make the content re-filter once a month is selected from the dropdown menu.

我发现在以下站点类似的查询: askthecssguy.com/2009/03/checkbox_filters_with_jquery_1.html

I have found similar inquires on the following site: askthecssguy.com/2009/03/checkbox_filters_with_jquery_1.html

和我也发现了类似的什么,我想这样做的工作例如:<一href="http://www.babycarers.com/search?ajax=0&searchref=37609&start=0&lat=&lon=&city=&radius=0&spec1=1&spec2=1&spec3=1&spec4=1&spec5=1&spec6=1&spec7=1&inst1=1&inst2=1&inst3=1&inst4=1&inst5=1&inst6=1&inst7=1&minfee=any&maxfee=any&av1=1&keywords=&country=CA&sort=fee&resultsperpage=10" rel="nofollow">http://www.babycarers.com/search?ajax=0&searchref=37609&start=0&lat=&lon=&city=&radius=0&spec1=1&spec2=1&spec3=1&spec4=1&spec5=1&spec6=1&spec7=1&inst1=1&inst2=1&inst3=1&inst4=1&inst5=1&inst6=1&inst7=1&minfee=any&maxfee=any&av1=1&keywords=&country=CA&sort=fee&resultsperpage=10

And I have found a working example similar to what I would like to do at: http://www.babycarers.com/search?ajax=0&searchref=37609&start=0&lat=&lon=&city=&radius=0&spec1=1&spec2=1&spec3=1&spec4=1&spec5=1&spec6=1&spec7=1&inst1=1&inst2=1&inst3=1&inst4=1&inst5=1&inst6=1&inst7=1&minfee=any&maxfee=any&av1=1&keywords=&country=CA&sort=fee&resultsperpage=10

如果有人可以帮助我的JavaScript / AJAX要退出这个功能,我将大大AP preciative。

If anyone could help me out with the javascript/Ajax necessary to pull this off I would be greatly appreciative.

推荐答案

几乎1000的观点,而不是一个单一的评论。嗯,我还需要这一点,并决定把它。我分享了JavaScript和话语preSS code以下的人在遥远的将来使用。它看起来像一个不少,但那是因为我定义你可以用 .extend 以后使用一些jQuery功能。所有它做的是寻找一个选择元素(下拉)与CSS类 .content过滤

Almost 1000 views and not a single comment. Well, I also needed this and decided to make it. I've shared the JavaScript and Wordpress code below for people in the distant future to use. It looks like a lot, but that's because I've defined some jQuery functions you can use later with .extend. All it's doing is looking for a select element (a dropdown) with CSS class .content-filter.

一旦发现,它采用了下拉的ID为GET变量设置为当前选择的值,然后将其重定向到这个相同的URL,并增加了这些GET变量。例如,如果下拉的id是 product_filter ,这有一个值设置为日期,然后它会设置GET变量 product_filter =日期。这是伟大的,因为它不关心你的Wordpess细节 - 所有它关心的是选择元素

Once found, it uses the dropdown's id to set a GET variable to the value currently selected, then it redirects to this the same URL and adds these GET variables. For example, if the id of the dropdown was product_filter, and this had a value set to date, then it would set the GET variable product_filter=date. It's great because it doesn't care about your Wordpess details - all it cares about is the select element.

// A bunch of helper methods for reading GET variables etc from the URL
jQuery.extend({
    urlGetVars : function() {
        var GET = {};
        var tempGET = location.search;
        tempGET = tempGET.replace('?', '').split('&');
        for(var i in tempGET) {
            var someVar = tempGET[i].split('=');
            if (someVar.length == 2) {
                GET[someVar[0]] = someVar[1];
            }
        }
        return GET;
    },
    urlGetVar : function(name) {
        return $.urlGetVars()[name];
    },
    serializeUrlVars : function(obj) {
        var str = [];
        for(var p in obj)
         str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    currentUrl : function() {
        return window.location.href.slice(0,window.location.href.indexOf('?'));
    }
});

// Adds functionality to filter content using a dropdown
var ContentFilter = function ($) {
    $(document).ready(function() {
        // Return to a scroll position if exists
        var scroll = $.urlGetVar('scroll');
        if (typeof scroll != 'undefined') {
            $(window).scrollTop(scroll);
        }
        // Prepare the filter dropdowns
        $('.content-filter').each(function(){
            var me = $(this);
            // e.g. content-filter-product
            var id = me.attr('id');
            // Refresh with selected filter on change
            var refresh = function() {
                var GET = $.urlGetVars();
                GET[id] = me.val();
                // Save scroll position, return to this position on load
                GET['scroll'] = $(window).scrollTop();
                var newVar = $.currentUrl() + '?' + $.serializeUrlVars(GET);
                window.location = newVar;
            };
            me.change(refresh);
        });
    });
}(jQuery);

现在的话preSS code。我们真正需要的是产生了选择与某种ID和类设置为 .content过滤。这code要求后型像后或产品,使选择的元素。然后,它返回的GET变量为了方便,如果没有设置则默认为最新。请注意, $领域阵列设置各种不同的排序依据值你想支持。您可以随时与 $ _ GET ['product_filter'] $ _ GET ['post_filter'] 这取决于你的类型。这意味着只有一个可以在任何给定的网页上生存,但是你想要的 - 否则jQuery将不知道用哪个。您可以扩展此code设置自定义ID或任何你以后想。

Now the Wordpress code. All we really need is to generate the select with some kind of id and set the class to .content-filter. This code asks for a post type like 'post' or 'product' and makes the select element. It then returns the GET variable for convenience, and if none is set then it defaults to 'newest'. Notice that the $fields array sets all the different orderby values you'd like to support. You can always access it anywhere in the template with $_GET['product_filter'] or $_GET['post_filter'] depending on what your type is. This means that only one can exist on any given page, but you want that - otherwise jQuery won't know which to use. You can extend this code to set a custom id or anything you like later.

function ak_content_filter($post_type_id = 'post', &$filter_get_value, $echo = TRUE) {
    $dropdown = '<div class="content-filter-wrapper">';
    // The dropdown filter id for this post type
    $filter_id = $post_type_id.'_filter';
    // The actual dropdown
    $dropdown .= '<label for="'. $filter_id .'">Filter</label><select id="'. $filter_id .'" class="content-filter" name="'. $filter_id .'">';
    // The available ways of filtering, to sort you'd need to set that in the WP_Query later
    $fields = array('date' => 'Newest', 'comment_count' => 'Most Popular', 'rand' => 'Random');
    $filter_get_value = isset($_GET[$filter_id]) ? $_GET[$filter_id] : 'newest'; // default is 'newest'
    foreach ($fields as $field_value=>$field_name) {
        $dropdown .= '<option value="'. $field_value .'" '. selected($field_value, $filter_get_value, FALSE) .'>'. $field_name .'</option>';
    }
    $dropdown .= '</select></div>';
    // Print or return
    if ($echo) {
        echo $dropdown;
    } else {
        return $dropdown;
    }
}

现在最有趣的部分 - 把它一起在内容页。我们所有的工作,有些甜,短code不负有心人:

Now the fun part - putting it together in the content page. All our work pays off with some sweet and short code:

// This will fill $product_filter with $_GET['product_filter'] or 'newest' if it doesn't exist
ak_content_filter('product', $product_filter);
$args = array('post_type' => 'product', 'orderby' => $product_filter);
// This is just an example, you can use get_pages or whatever supports orderby
$loop = new WP_Query( $args );

// OR, to avoid printing:
$dropdown = ak_content_filter('product', $product_filter, FALSE);
// ... some code ...
echo $dropdown;

我使用的自定义职位类型'产品',但如果你使用'后'刚刚更换。有人也许应该做成插件这个,如果他们还没有:P

I used the custom post type 'product', but if you're using 'post' just replace that. Someone should probably make this into a plugin if they haven't already :P

这篇关于动态筛选字preSS职位与下拉菜单(使用PHP和AJAX)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆