【问题标题】:Wordpress - save filter settings into cookieWordpress - 将过滤器设置保存到 cookie 中
【发布时间】:2020-01-19 18:36:53
【问题描述】:

我在 Wordpress 中有自定义帖子类型,带有自定义过滤器。

我希望能够将用户的过滤器保存到 cookie 中,这样当他返回帖子列表时,他的最后一个过滤器会自动设置。

我有保存 cookie 的代码:

function set_newuser_cookie() {
    if ( is_admin() && $_GET['post_type'] == 'tickets') {

        setcookie('bs_tickets_filter', $_SERVER['QUERY_STRING'], time()+3600*24*100, COOKIEPATH, COOKIE_DOMAIN, false);

    }
}
add_action( 'init', 'set_newuser_cookie'); 

此代码将整个查询字符串保存到 cookie 中,类似于:

orderby=status&order=asc&s&post_status=all&post_type=tickets&action=-1&m=0&status=0&type=0&priority=0&state=2135&author&paged=1&mode=list&action2=-1

当用户返回帖子列表时,如何再次设置过滤器?

【问题讨论】:

    标签: php wordpress cookies


    【解决方案1】:

    我想我解决了这个问题:

    function bs_set_filter_cookie() {
        if ( is_admin() && $_GET['post_type'] == 'tickets' ) {
          // if theres filter request, update cookie
          if (isset($_GET['status'])) {
            $query = http_build_query($_GET); 
            setcookie('bs_tickets_filter', $query, time()+3600*24*100, COOKIEPATH, COOKIE_DOMAIN, false);
       }
      }
    
      // if there's no filter request, add variable to $_GET
      if (!isset($_GET['status'])) {
         parse_str($_COOKIE["bs_tickets_filter"], $output);
         foreach ($output as $key => $val) {
            $_GET[$key] = $val;
         }
    
      }
    }
    add_action( 'init', 'bs_set_filter_cookie'); 
    

    【讨论】:

      【解决方案2】:

      刚刚发现用于类似的东西 - 只是我希望 WP 记住我的过滤器的常规类别。

      add_action( 'init', 'set_filter_cookie'); 
      function set_filter_cookie() {
          if (is_admin() && !empty($_GET)) {
              $cur_php = basename($_SERVER['PHP_SELF']);
              if ( $cur_php == "edit.php" && isset($_GET['post_type']) ){
                  if ( $_GET['post_type'] == 'page' ) { 
                      // if theres filter request, update cookie
                      if (isset($_GET['cat'])) {
                          $query = http_build_query($_GET); 
                          setcookie(category_filter', $query, time()+3600*24*100, COOKIEPATH, COOKIE_DOMAIN, false);
                      }
                      // if there's no filter request, add variable to $_GET we look for cookie
                      if (!isset($_GET['cat'])) {
                          if(isset($_COOKIE['category_filter'])) {
                              parse_str($_COOKIE['category_filter'], $output);
                              foreach ($output as $key => $val) {
                                  $_GET[$key] = $val;
                              }
                          }
                      }
                  }       
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        • 2015-02-13
        • 1970-01-01
        相关资源
        最近更新 更多