Advertisement
Guest User

henri

a guest
Jan 28th, 2010
395
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 35.44 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: WP Smart Sort
  4. Plugin URI: http://dyasonhat.com/wp-smart-sort/
  5. Description: Advanced posts sorting for wordpress. Sort by various fields including custom fields.
  6. Author: dyasonhat
  7. Version: 2.1.2
  8. Author URI: http://dyasonhat.com/
  9. */
  10. /*
  11. Changelog
  12. 2.1.2
  13.     Fixed pages dissapearing in the admin screen.
  14.     Fixed posts repeating themselves.
  15. 2.1.1
  16.     Fixed viewing individual tag pages bug.
  17. 2.1.0
  18.     Admin UI upgraded to 2.7 style
  19.     Support for all permalink varieties including default eg ?cat=4
  20.     Set default sort direction for individual category pages.
  21.     Fixed bug with static pages dissapearing with plugin activation.
  22.     Updated readme.txt
  23. 2.0.3
  24.     Update readme to indicate $wpss->placesort()
  25. 2.0.2
  26.     Version number bump for svn issue
  27. 2.0.1
  28.     Fix for Sort dropdown navigation and Safari Browser
  29. 2.0.0
  30.     All new release.
  31. */    
  32. class WP_Smart_Sort {
  33.    
  34.  
  35.     function ss_init() {
  36.         global $wp_rewrite;
  37.        
  38.            $wp_rewrite->flush_rules();
  39.        
  40.     }
  41.    
  42.     function ss_rewrite($wp_rewrite) {
  43.         /*$keywords_structure,
  44.                 $ep_mask = EP_NONE,
  45.                 $page = true,
  46.                 $feed = true,
  47.                 $forcomments = false,
  48.                 $walk_dirs = true); */
  49.         /*
  50.         * SORT REWRITE RULES
  51.         */
  52.         $sort_token = '%ssort%';
  53.         $wp_rewrite->add_rewrite_tag($sort_token, '(.+?)', "ssort=");
  54.        
  55.         $keywords_structure = array();
  56.         //index
  57.         $keywords_structure[] = $wp_rewrite->root . "/";
  58.         //categories
  59.         $keywords_structure[] = $wp_rewrite->category_structure . "/";
  60.         //tag
  61.         $keywords_structure[] = $wp_rewrite->tag_structure . "/";
  62.         //author
  63.         $keywords_structure[] = $wp_rewrite->author_structure . "/";
  64.         //date
  65.         //year
  66.         $keywords_structure[] = $wp_rewrite->get_year_permastruct() . "";
  67.         //month
  68.         $keywords_structure[] = $wp_rewrite->get_month_permastruct() . "";
  69.         //day
  70.         $keywords_structure[] = $wp_rewrite->get_day_permastruct() . "/";
  71.            
  72.         foreach ($keywords_structure as $keyword_structure) {
  73.             $wp_rewrite->rules = $wp_rewrite->generate_rewrite_rules($keyword_structure . "sort/$sort_token", EP_NONE, true, true, false, false) + $wp_rewrite->rules;
  74.         }
  75.  
  76.     }
  77.  
  78.     function ss_insert_my_rewrite_query_vars($vars) {
  79.       $vars[] = 'ssort';
  80.       $vars[] = 'sdir';
  81.       return $vars;
  82.     }
  83.    
  84.     function ss_get_term_id_by_slug ($slug, $taxonomy) {
  85.         global $wpdb;
  86.        
  87.        
  88.         return $id;
  89.     }
  90.    
  91.     function ss_get_current_context_url(){
  92.         global $wp_query;
  93.         global $wpdb;
  94.  
  95.         $url = '';
  96.         if (is_category()) {
  97.             $cat_id = $wp_query->get('cat');
  98.             $url = get_category_link($cat_id);
  99.         }
  100.         elseif (is_tag()) {
  101.            $tag_name = $wp_query->get('tag');
  102.            $sql = "SELECT ".$wpdb->terms.".term_id FROM $wpdb->term_taxonomy
  103.                                    LEFT JOIN $wpdb->terms
  104.                                    ON (".$wpdb->term_taxonomy.".term_id = ".$wpdb->terms.".term_id)
  105.                                    WHERE ".$wpdb->terms.".slug = '$tag_name'
  106.                                    AND ".$wpdb->term_taxonomy.".taxonomy = 'post_tag'
  107.                                    LIMIT 1";
  108.            $tag_id = $wpdb->get_var($sql);
  109.            $url = get_tag_link($tag_id);
  110.         }
  111.         elseif (is_author()) {
  112.             $author_id = $wp_query->get('author');
  113.             $url = get_author_posts_url($author_id);
  114.         }
  115.         elseif (is_date()) {
  116.             $year = $wp_query->get('year');
  117.             $month = $wp_query->get('monthnum');
  118.             $day = $wp_query->get('day');
  119.            
  120.             if ($wp_query->get('day')) {
  121.                 $url = get_day_link( $year,  $month,  $day);
  122.             }
  123.             elseif ($wp_query->get('monthnum')) {
  124.                 $url = get_month_link( $year,  $month,  $day);
  125.             }
  126.             elseif ($wp_query->get('year')) {
  127.                 $url = get_year_link( $year,  $month,  $day);
  128.             }
  129.         }
  130.         else {
  131.             $url = get_bloginfo('url');
  132.         }
  133.        
  134.         if ($this->ss_use_permalinks()) {
  135.             //ensure trailing slash
  136.             if ("/" != substr($url, -1)) {
  137.                 $url = $url . "/";
  138.             }
  139.         }
  140.         return $url;
  141.     }
  142.    
  143.     function ss_use_permalinks () {
  144.        
  145.         $permalink = get_option("permalink_structure");
  146.        
  147.         if ($permalink == "") {
  148.             return false;
  149.         }
  150.         else {
  151.             return true;
  152.         }
  153.     }
  154.    
  155.     function ss_widget_sort ($args){
  156.         extract($args);
  157.         ?>
  158.         <?php echo $before_widget; ?>
  159.           <?php echo $before_title
  160.               . 'Sort By'
  161.               . $after_title; ?>
  162.           <?php $this->placesort(); ?>
  163.         <?php echo $after_widget;
  164.     }
  165.    
  166.     function ss_plugins_loaded () {
  167.         register_sidebar_widget("Smart Sort",array($this, "ss_widget_sort"));
  168.     }
  169.    
  170.     function placesort() {
  171.  
  172.         $sort_drop_title = get_option('ss_sort_drop_down_title');
  173.         $saved_options = $this->ss_get_options();
  174.         $ssort = $this->ss_open_ssort();
  175.         $sorthtml = '<select name="ssort" onChange="document.location.href=this.options[this.selectedIndex].value;">';
  176.        
  177.         foreach ($saved_options as $option) {
  178.             $selected = '';
  179.             if ($option['nicekey']."-asc" == $ssort['sort'] . "-" . strtolower($ssort['dir'])) {
  180.                 $selected = "selected";
  181.             }
  182.             $sorthtml .= "<option value='".$option['asclink']."' $selected onClick='window.location = \"".$option['asclink']."\"; return false;' >".$option['title']." ". __('&uarr;')."</option>";
  183.            
  184.             $selected = '';
  185.             if ($option['nicekey']."-desc" == $ssort['sort'] . "-" . strtolower($ssort['dir'])) {
  186.                 $selected = "selected";
  187.             }
  188.             $sorthtml .= "<option value='".$option['desclink']."' $selected onClick='window.location = \"".$option['desclink']."\"; return false;' >".$option['title']." ". __('&darr;')."</option>";
  189.         }
  190.         $sorthtml .= '</select>';
  191.        
  192.         echo "$sorthtml";
  193.     }
  194.    
  195.     function ss_add_pages() {
  196.         // Add a new menu under Options:
  197.         add_options_page('WP Smart Sort', 'WP Smart Sort', 8, __FILE__, array($this, 'ss_options_sort_page'));
  198.     }
  199.  
  200.     function ss_orderby($sort) {
  201.  
  202.         $ssort = $this->ss_open_ssort();
  203.         if ( (is_tag() OR is_category() OR is_author() OR is_date() OR is_home()) ) {
  204.            
  205.             $sort  = $ssort['sortfield'];
  206.             if ($ssort['isnumerical']) {
  207.                 $sort = "(" . $sort . "+0)";
  208.             }
  209.             $dir    = $ssort['dir'];
  210.             return " $sort $dir ";
  211.         }
  212.        
  213.         return $sort;
  214.     }
  215.  
  216.     function ss_join($jn){
  217.         global $wpdb;
  218.        
  219.         $ssort = $this->ss_open_ssort();    
  220.        
  221.         if ( ($ssort['ismeta'] === true) AND (is_tag() OR is_category() OR is_author() OR is_date() OR is_home()) ) {
  222.             return $jn . "LEFT JOIN $wpdb->postmeta ON ($wpdb->posts".".ID = $wpdb->postmeta".".post_id)";
  223.         }                                                                                                    
  224.                                                                                                              
  225.         return $jn;
  226.     }
  227.     /*
  228.     * Returns an array containing all the saved sort options
  229.     */
  230.     function ss_get_options () {
  231.        
  232.         if (get_option("ss_sort_item")) {
  233.             $compound_options = get_option("ss_sort_item");
  234.             $semi_compound_options = explode("---", $compound_options);
  235.            
  236.             $ss_options = array();
  237.            
  238.             foreach ($semi_compound_options as $semi_o) {
  239.                 $option['key'] = "";
  240.                 $option['nicekey'] = "";
  241.                 $option['numerical'] = "";
  242.                 $option['title'] = "";
  243.                
  244.                 $compound_key = substr($semi_o,0, strpos($semi_o,"{"));
  245.                
  246.                 $compound_key = explode("::", $compound_key);
  247.                 $option['nicekey'] = array_pop($compound_key);
  248.                 $option['key'] = implode("::", $compound_key);
  249.                 $key = $option['nicekey'];
  250.                        
  251.                 $key_values = substr($semi_o, (strpos($semi_o,"{")+1), (strrpos($semi_o,"}") - strpos($semi_o,"{")-1) );
  252.                 $key_values = explode("::", $key_values);
  253.                
  254.                 $option['numerical'] = array_pop($key_values);
  255.                 $option['title'] = implode("::", $key_values);
  256.                
  257.                 if ($this->ss_use_permalinks()) {
  258.                     $option['asclink'] = $this->ss_get_current_context_url() . 'sort/' . $option['nicekey'] . '-asc/';
  259.                     $option['desclink'] = $this->ss_get_current_context_url() . 'sort/' . $option['nicekey'] . '-desc/';
  260.                 } else {
  261.                     $url = parse_url($this->ss_get_current_context_url());
  262.                     $url = $url['scheme'] . "://" . $url['host'] . $url['path'] . "?" . $url['query'];
  263.                     $option['asclink'] = $url . '&ssort=' . $option['nicekey'] . '&sdir=asc';
  264.                     $option['desclink'] = $url . '&ssort=' . $option['nicekey'] . '&sdir=desc';
  265.                 }
  266.                 $ss_options["$key"] = $option;
  267.             }
  268.         }
  269.         else {
  270.             add_option("ss_sort_item","");
  271.             $ss_options = array();        
  272.         }
  273.            
  274.         return $ss_options;
  275.     }
  276.    
  277.     //Returns the default sort direction for the current context
  278.     function ss_get_default_sort_direction () {
  279.         global $wp_query;
  280.         global $wpdb;
  281.         if (is_category()) {
  282.            
  283.             $sort = $this->ss_multicontext_open_options("categories");
  284.             $cat_id = $wp_query->get('cat');
  285.             if (array_key_exists($cat_id, $sort)) {
  286.                 $sortvar = $sort[$cat_id]['sort'];
  287.             }
  288.             else {
  289.                 $sortvar = false;
  290.             }
  291.                
  292.         }
  293.         elseif (is_tag()) {
  294.            
  295.             $sort = $this->ss_multicontext_open_options("tags");
  296.             $tag_name = $wp_query->get('tag');
  297.             $sql = "SELECT ".$wpdb->terms.".term_id FROM $wpdb->term_taxonomy
  298.                                    LEFT JOIN $wpdb->terms
  299.                                    ON (".$wpdb->term_taxonomy.".term_id = ".$wpdb->terms.".term_id)
  300.                                    WHERE ".$wpdb->terms.".slug = '$tag_name'
  301.                                    AND ".$wpdb->term_taxonomy.".taxonomy = 'post_tag'
  302.                                    LIMIT 1";
  303.             $tag_id = $wpdb->get_var($sql);
  304.             if (array_key_exists(tag_id, $sort)) {
  305.                 $sortvar = $sort[$tag_id]['sort'];
  306.             }
  307.             else {
  308.                 $sortvar = false;
  309.             }
  310.          
  311.         }
  312.         else {
  313.             $sortvar = get_option('ss_default_sort_direction');
  314.         }
  315.        
  316.         if ($sortvar === false) {
  317.             $sortvar = get_option('ss_default_sort_direction');
  318.         }        
  319.        
  320.         return $sortvar;
  321.     }
  322.    
  323.     function ss_open_ssort () {
  324.         global $wpdb;
  325.         global $wp_query;
  326.        
  327.         $dir = "";    
  328.         //Direction
  329.         if ($wp_query->get('sdir')) {
  330.            $dir = $wp_query->get('sdir');
  331.         }
  332.         else {
  333.             $dir = "DESC";
  334.         }
  335.        
  336.         if ($wp_query->get('ssort')) {
  337.            $sortvar = $wp_query->get('ssort');
  338.         }
  339.         else {
  340.             $sortvar = $this->ss_get_default_sort_direction();
  341.         }
  342.        
  343.         $str1 = substr($sortvar, strlen($sortvar)-4, 4);
  344.         $str2 = substr($sortvar, strlen($sortvar)-5, 5);
  345.         if ($str1 == '-asc') {
  346.             $dir = "ASC";
  347.             $sortby = substr($sortvar, 0, strlen($sortvar)-4);
  348.         } elseif ($str2 == "-desc") { //ensures the ASC is at the end of the string which means ASC and not found in the string elsewhere eg sort=nascar-desc
  349.             $dir = "DESC";
  350.             $sortby = substr($sortvar, 0, strlen($sortvar)-5);
  351.         }
  352.         else {
  353.             //$dir = false;
  354.             $sortby = $sortvar;
  355.         }
  356.        
  357.         $ssort['dir'] = $dir;
  358.         $ssort['sort'] = $sortby;
  359.         $ssort['isnumerical'] = false;
  360.        
  361.         $field_type = substr($sortby,-3);
  362.         $saved_options = $this->ss_get_options();
  363.         if ($field_type == "-pm") { // its a meta sort
  364.             $metatable = $wpdb->postmeta;
  365.             $cf_name = $saved_options["$sortby"]['key'];
  366.             $ssort['nicekey'] = $saved_options["$sortby"]['nicekey'];
  367.             $ssort['fieldkey'] = substr($cf_name, strlen($metatable)+1, strlen($cf_name) - strlen($metatable) - 1);
  368.             $ssort['sortfield'] = $metatable . ".meta_value";
  369.             $ssort['ismeta'] = true;
  370.             if ($saved_options["$sortby"]['numerical'] == '1') {
  371.                 $ssort['isnumerical'] = true;
  372.             }
  373.         }
  374.         elseif ($field_type == "-pp") { // its a post table sort
  375.             $posttable = $wpdb->posts;
  376.             $cf_name = $saved_options["$sortby"]['key'];
  377.             $ssort['nicekey'] = $saved_options["$sortby"]['nicekey'];
  378.             $ssort['fieldkey'] = substr($cf_name, strlen($posttable)+1, strlen($cf_name) - strlen($posttable) - 1);
  379.             $ssort['sortfield'] = $posttable . "." . $ssort['fieldkey'];
  380.             $ssort['ismeta'] = false;
  381.             if ($saved_options["$sortby"]['numerical'] == '1') {
  382.                 $ssort['isnumerical'] = true;
  383.             }
  384.         }
  385.         else {
  386.             $ssort['sortfield'] = $sortby;
  387.             $ssort['ismeta'] = false;
  388.         }
  389.        
  390.         if (!$ssort['sortfield']) {$ssort['sortfield'] = "post_date"; }
  391.         if (!$ssort['dir']) {$ssort['dir'] = "DESC"; }
  392.         if ($ssort['ismeta'] !== true) {$ssort['ismeta'] = false; }
  393.        
  394.         return $ssort;
  395.        
  396.     }
  397.    
  398.     function ss_make_nice_key ($key) {
  399.         global $wpdb;
  400.         $metatable = $wpdb->prefix . "postmeta";
  401.         $posttable = $wpdb->prefix . "posts";
  402.        
  403.         if (substr($key, 0, strlen($metatable)) == $metatable) { // is a meta table key
  404.             $field = substr($key, strlen($metatable), strlen($key) - strlen($metatable) );
  405.             $field = ereg_replace("[^A-Za-z0-9]", "_", $field );
  406.             $new_key = $field . "-pm";
  407.         }
  408.         elseif (substr($key, 0, strlen($posttable)) == $posttable) { //is a post table key
  409.             $field = substr($key, strlen($posttable), strlen($key) - strlen($posttable) );
  410.             $field = ereg_replace("[^A-Za-z0-9]", "_", $field );
  411.             $new_key = $field . "-pp";    
  412.         }
  413.         else { //dunno what it is
  414.             $new_key = $key;
  415.         }
  416.        
  417.         return $new_key;
  418.     }
  419.     /*
  420.     * Produces a single compounded option
  421.     */
  422.     function ss_make_option ($key, $title, $numerical) {
  423.         $option = $key . "::" . $this->ss_make_nice_key($key) . "{" . $title . "::" . $numerical . "}";
  424.         return $option;
  425.     }
  426.  
  427.     /*
  428.     * Adds an option to the sort options list
  429.     */
  430.     function ss_add_option ($option) {
  431.        
  432.         if (get_option("ss_sort_item") !== false){
  433.             $current = get_option("ss_sort_item");
  434.             if ($current != '') {
  435.                 $new = $current . "---" . $option;
  436.             }
  437.             else {
  438.                 $new = $option;
  439.             }
  440.            
  441.             update_option("ss_sort_item", $new);
  442.         }
  443.         else {
  444.             add_option("ss_sort_item", $option);
  445.         }
  446.        
  447.     }
  448.     /*
  449.     * Deletes an option from the sort options list
  450.     */
  451.     function ss_delete_option ($nicekey) {
  452.        
  453.         $saved_options = $this->ss_get_options();
  454.         $newitems = array();
  455.        
  456.         foreach($saved_options as $option){
  457.             if ($option['nicekey'] != $nicekey){
  458.                 $newitems[] = $this->ss_make_option($option['key'],$option['title'],$option['numerical']);
  459.             }
  460.         }
  461.         $this->ss_save_total_options($newitems);
  462.        
  463.     }
  464.     /*
  465.     * Saves the sort options to wp_options
  466.     * @param options is an array.
  467.     */
  468.     function ss_save_total_options ($options) {
  469.        
  470.         $total_options = implode("---",$options);
  471.        
  472.         if (get_option("ss_sort_item")){
  473.             update_option("ss_sort_item", $total_options);
  474.         }
  475.         else {
  476.             add_option("ss_sort_item", $total_options);
  477.         }
  478.        
  479.     }
  480.    
  481.     function ss_update_option($sortkey, $newoption) {
  482.  
  483.         $saved_options = $this->ss_get_options();
  484.         $newitems = array();
  485.        
  486.         foreach($saved_options as $option){
  487.             if ($option['key'] == $sortkey){
  488.                 $newitems[] = $newoption;
  489.             }
  490.             else {
  491.                 $newitems[] =$this-> ss_make_option($option['key'],$option['title'],$option['numerical']);
  492.             }
  493.         }
  494.         $this->ss_save_total_options($newitems);
  495.        
  496.     }
  497.    
  498.     function ss_multicontext_open_options($type) {
  499.         $all_multi = array();
  500.        
  501.          switch ($type) {
  502.             case "categories":
  503.                 $glob = get_option("ss_category_sort_direction");
  504.                
  505.                 $saved_options = explode("{}", $glob);
  506.                 foreach ($saved_options as $svd) {
  507.                     $tmpvar = explode("~",$svd);
  508.                     $id = $tmpvar[0];
  509.                     $name = $tmpvar[1];
  510.                     $sort = $tmpvar[2];
  511.                     $tmpvar2 = array ( "id"    =>  $id,
  512.                                         "name"  =>  $name,
  513.                                         "sort"  =>  $sort
  514.                                         );
  515.                                            
  516.                     $all_multi[$id] = $tmpvar2;            
  517.                 }
  518.                 break;
  519.             case 'tags':
  520.                 $glob = get_option("ss_tag_sort_direction");
  521.                
  522.                 $saved_options = explode("{}", $glob);
  523.                 foreach ($saved_options as $svd) {
  524.                     $tmpvar = explode("~",$svd);
  525.                     $id = $tmpvar[0];
  526.                     $name = $tmpvar[1];
  527.                     $sort = $tmpvar[2];
  528.                     $tmpvar2 = array ( "id"    =>  $id,
  529.                                         "name"  =>  $name,
  530.                                         "sort"  =>  $sort
  531.                                         );
  532.                                            
  533.                     $all_multi[$id] = $tmpvar2;            
  534.                 }
  535.                 break;
  536.          }
  537.        
  538.         return $all_multi;
  539.     }
  540.     //Created the string to be saved in the dB.
  541.     function ss_multicontext_close_options($type, $options) {
  542.         $savestr = array();
  543.        
  544.         foreach ($options as $option) {
  545.             $savestr[] = $option['id'] . "~" . $option['name'] . "~" . $option['sort'];
  546.         }
  547.         $savestr = implode("{}", $savestr);
  548.        
  549.         //echo "Saving: $savestr <br>";
  550.         if (!(update_option("ss_".$type."_sort_direction",$savestr))) {
  551.             add_option("ss_".$type."_sort_direction",$savestr);
  552.         }
  553.        
  554.        
  555.     }
  556.    
  557.     function ss_multicontext_sort_options ($type) {
  558.         global $wpdb;
  559.        
  560.         $cxv = array();
  561.        
  562.         switch ($type) {
  563.             case "categories":
  564.                 $sql = "SELECT term_taxonomy_id, slug, name FROM $wpdb->terms
  565.                    LEFT JOIN $wpdb->term_taxonomy ON
  566.                    ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id)
  567.                    
  568.                    WHERE taxonomy = 'category'";
  569.            
  570.                 $categories = $wpdb->get_results($sql);
  571.                 $saved = $this->ss_multicontext_open_options($type);
  572.                
  573.                 foreach ($categories as $cat) {
  574.                     $tmp = array();
  575.                     $tmp["name"] = $cat->name;
  576.                     $tmp["slug"] = $cat->slug;
  577.                     $tmp["id"] = $cat->term_taxonomy_id;
  578.                    
  579.                     $tmp['sort'] = $this->ss_get_default_sort_direction();
  580.                     foreach ($saved as $ct) {
  581.                         if ($tmp['id'] == $ct['id']) {
  582.                             $tmp['sort'] = $ct['sort'];
  583.                         }
  584.                     }
  585.                    
  586.                     $cxv[$tmp['id']] = $tmp;
  587.                
  588.                 }
  589.                
  590.               break;
  591.              
  592.             case "tags":
  593.                   $sql = "SELECT term_taxonomy_id, slug, name FROM $wpdb->terms
  594.                    LEFT JOIN $wpdb->term_taxonomy ON
  595.                    ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id)
  596.                    WHERE taxonomy = 'post_tag'";
  597.                   $tags = $wpdb->get_results($sql);
  598.                  
  599.                   $saved = $this->ss_multicontext_open_options($type);
  600.                
  601.                  foreach ($tags as $tag) {
  602.                     $tmp = array();
  603.                     $tmp["name"] = $tag->name;
  604.                     $tmp["slug"] = $tag->slug;
  605.                     $tmp["id"] = $tag->term_taxonomy_id;
  606.                    
  607.                     $tmp['sort'] = $this->ss_get_default_sort_direction();
  608.                     foreach ($saved as $ct) {
  609.                         if ($tmp['id'] == $ct['id']) {
  610.                             $tmp['sort'] = $ct['sort'];
  611.                         }
  612.                     }
  613.                    
  614.                     $cxv[$tmp['id']] = $tmp;
  615.                
  616.                  }
  617.               break;
  618.          }
  619.          
  620.    
  621.         return $cxv;
  622.     }
  623.    
  624.     //creates the drop down menu for selecting default sort directions
  625.     function ss_make_admin_sort_select($name, $selected) {
  626.         $opt_fields = $this->ss_get_options();
  627.         $dsort = "<select name='$name'>";
  628.        
  629.         foreach ($opt_fields as $field) {
  630.             $nicekey = $field['nicekey'];
  631.             $title = $field['title'];
  632.             if ($nicekey . "-asc" == $selected) {
  633.                 $sel1 = "selected";
  634.                 $sel2 = "";
  635.             }
  636.             elseif ($nicekey . "-desc" == $selected) {
  637.                 $sel1 = "";
  638.                 $sel2 = "selected";
  639.             }
  640.             else {
  641.                 $sel1 = "";
  642.                 $sel2 = "";
  643.             }
  644.        
  645.             $dsort .= "<option value='$nicekey-asc' $sel1 >$title ($nicekey) " . __('ASC'). "</option>";
  646.             $dsort .= "<option value='$nicekey-desc' $sel2 >$title ($nicekey) ". __('DESC'). "</option>";
  647.         }
  648.         $dsort .= "</select>";
  649.        
  650.         return $dsort;
  651.        
  652.        
  653.     }
  654.    
  655.     //OPTIONS Sort Page
  656.     function ss_options_sort_page() {
  657.         global $_POST;
  658.         global $_POST;
  659.         global $wpdb;
  660.        
  661.        
  662.         $saved_options = $this->ss_get_options();
  663.          
  664.         if ($_POST['action'] == 'add'){
  665.             if ($_POST['sortkey'] and $_POST['sorttitle']){
  666.                
  667.                 $option = $this->ss_make_option($_POST['sortkey'],$_POST['sorttitle'],$_POST['numerical']);
  668.                 $this->ss_add_option ($option);
  669.                
  670.             }
  671.         } else if ($_POST['action'] == 'delete'){
  672.             if ($_POST['sortkey']){
  673.                
  674.                 $this->ss_delete_option($this->ss_make_nice_key($_POST['sortkey']));
  675.                
  676.             }
  677.         } else if ($_POST['action'] == 'update'){
  678.             if ($_POST['sortkey']){
  679.                
  680.                 $option =  $this->ss_make_option($_POST['sortkey'],$_POST['sorttitle'],$_POST['numerical']);
  681.                 $this->ss_update_option($_POST['sortkey'], $option);
  682.             }
  683.         } else if ($_POST['action'] == 'categories-update'){
  684.             $options = array();
  685.             foreach ($_POST as $p => $a) {
  686.                 if (($a != 'categories-update') AND ($a != __('Save Changes'))) {
  687.                     $option = array();
  688.                    
  689.                     $id = substr($p, strrpos($p, "_") + 1, strlen($p) - (strrpos($p, "_") + 1 ));
  690.                     $name = get_cat_name($id);
  691.                    
  692.                     $option['id'] = $id;
  693.                     $option['name'] = $name;
  694.                     $option['sort'] = $a;
  695.                    
  696.                     $options[] = $option;
  697.                    
  698.                 }
  699.             }
  700.             $this->ss_multicontext_close_options('category', $options);
  701.         }
  702.        
  703.        
  704.         /*
  705.         * Get the available fields from "CUSTOM FIELDS"
  706.         */
  707.         $saved_options = $this->ss_get_options();
  708.         $res    =   $wpdb->get_results("SELECT meta_key FROM $wpdb->postmeta GROUP BY meta_key");
  709.         $meta_fields_html = '';
  710.         foreach ($res as $des ) {
  711.            
  712.             $key = $wpdb->prefix."postmeta." . $des->meta_key;
  713.             $showkey = ucwords($des->meta_key);
  714.             $nicekey = $this->ss_make_nice_key($key);
  715.             $html =    '<table class="form-table">';
  716.             $html .=   '<tr valign="top">
  717.                        <th scope="row">' . $showkey . '</th>';
  718.             $html .=   '<td>';
  719.            
  720.             if ( array_key_exists($nicekey, $saved_options) ) {
  721.                
  722.                 $html .='
  723.                        <form method="post" action="">
  724.                            <div style="float:right">
  725.                                <input type="hidden" name="sortkey" value="'.$key.'" />
  726.                                <input type="hidden" name="action" value="delete" />                            
  727.                                <input type="submit" class="button"  name="Submit" value="'. __('Remove') .'" />
  728.                            </div>
  729.                        </form>
  730.                        <form method="post" action="">
  731.                            <div style="float:right">
  732.                                <input type="hidden" name="sortkey" value="'.$key.'" />
  733.                                <input type="hidden" name="action" value="update" />
  734.                                <input type="submit" class="button"  name="Submit" value="'. __('Update') .'" />
  735.                            </div>
  736.                        ';
  737.             } else {
  738.                 $html .='<form method="post" action="">
  739.                            <div style="float:right">                    
  740.                                <input type="hidden" name="sortkey" value="'.$key.'" />
  741.                                <input type="hidden" name="action" value="add" />
  742.                                <input type="submit" class="button" name="Submit" value="'. __('Add') .'" />
  743.                            </div>
  744.                        ';
  745.             }
  746.            
  747.            
  748.             $html .='<div>';
  749.             $html .='<div>
  750.                     <label for="sorttitle" />'. __('Display Text').'</label>
  751.                     <input type="text" name="sorttitle" value="'.$saved_options[$nicekey]['title'].'" />
  752.                     </div>';
  753.            
  754.             $checked = '';
  755.             if ($saved_options[$nicekey]['numerical'] == '1') {
  756.                 $checked = 'checked="checked"';
  757.             }
  758.            
  759.             $html .='<div>
  760.                     <label for="numerical" />'. __('Is Numeric').'</label>
  761.                     <input type="checkbox" name="numerical" value="1" '.$checked.'/>
  762.                     </div>';
  763.                      
  764.             $html .='</div></form></td></tr></table>';    
  765.             $meta_fields_html .= $html;
  766.         }
  767.        
  768.         /*
  769.         * Get the available fields from "Posts Table"
  770.         */
  771.         $res    =   $wpdb->get_results("DESCRIBE $wpdb->posts");    
  772.         $posts_fields_html = '';
  773.         foreach ($res as $des ) {
  774.            
  775.             $key = $wpdb->prefix."posts." . $des->Field;
  776.             $showkey = ucwords($des->Field);
  777.             $nicekey = $this->ss_make_nice_key($key);
  778.             $html =    '<table class="form-table">';
  779.             $html .=   '<tr valign="top">
  780.                        <th scope="row">' . $showkey . '</th>';
  781.             $html .=   '<td>';
  782.            
  783.             if ( array_key_exists($nicekey, $saved_options) ) {
  784.                
  785.                 $html .='
  786.                        <form method="post" action="">
  787.                            <div style="float:right">
  788.                                <input type="hidden" name="sortkey" value="'.$key.'" />
  789.                                <input type="hidden" name="action" value="delete" />                            
  790.                                <input type="submit" class="button"  name="Submit" value="'. __('Remove') .'" />
  791.                            </div>
  792.                        </form>
  793.                        <form method="post" action="">
  794.                            <div style="float:right">
  795.                                <input type="hidden" name="sortkey" value="'.$key.'" />
  796.                                <input type="hidden" name="action" value="update" />
  797.                                <input type="submit" class="button"  name="Submit" value="'. __('Update') .'" />
  798.                            </div>
  799.                        ';
  800.             } else {
  801.                 $html .='<form method="post" action="">
  802.                            <div style="float:right">                    
  803.                                <input type="hidden" name="sortkey" value="'.$key.'" />
  804.                                <input type="hidden" name="action" value="add" />
  805.                                <input type="submit" class="button" name="Submit" value="'. __('Add') .'" />
  806.                            </div>
  807.                        ';
  808.             }
  809.            
  810.            
  811.             $html .='<div>';
  812.             $html .='<div>
  813.                     <label for="sorttitle" />'. __('Display Text').'</label>
  814.                     <input type="text" name="sorttitle" value="'.$saved_options[$nicekey]['title'].'" />
  815.                     </div>';
  816.            
  817.             $checked = '';
  818.             if ($saved_options[$nicekey]['numerical'] == '1') {
  819.                 $checked = 'checked="checked"';
  820.             }
  821.            
  822.             $html .='<div>
  823.                     <label for="numerical" />'. __('Is Numeric').'</label>
  824.                     <input type="checkbox" name="numerical" value="1" '. $checked .'/>
  825.                     </div>';
  826.                      
  827.             $html .='</div></form></td></tr></table>';    
  828.             $posts_fields_html .= $html;
  829.         }
  830.        
  831.         ?><div class='wrap'>
  832.                 <h2>WP Smart Sort</h2>
  833.                 <P align=center>
  834.                 <div class="metabox-holder" id="poststuff">
  835.                     <div class="postbox">
  836.                         <h3 class="hndle"><?php _e('From Custom Fields'); ?></h3>
  837.                             <div class="inside">
  838.                                 <?php echo $meta_fields_html; ?>
  839.                             </div>
  840.                     </div>
  841.                     <div class="postbox">
  842.                         <h3 class="hndle"><?php _e('From WP Posts Table'); ?></h3>
  843.                             <div class="inside">
  844.                                 <?php echo $posts_fields_html; ?>
  845.                             </div>
  846.                     </div>
  847.                     <div class="postbox">
  848.                         <h3 class="hndle"><?php _e('Other Options'); ?></h3>
  849.                         <div class="inside">
  850.                             <form method="post" action="options.php">
  851.                             <?php wp_nonce_field('update-options'); ?>
  852.                             <table class="form-table">
  853.                                 <tr valign="top">
  854.                                     <th scope="row"><?php _e('Default Sort Direction'); ?></th>
  855.                                     <td><?php
  856.                                    
  857.                                             //$contexts = $this->ss_multicontext_sort_options();
  858.                                             echo $this->ss_make_admin_sort_select('ss_default_sort_direction', $this->ss_get_default_sort_direction());
  859.                                         ?></td>
  860.                                 </tr>
  861.                             </table>
  862.  
  863.                             <input type="hidden" name="action" value="update" />
  864.                             <input type="hidden" name="page_options" value="ss_default_sort_direction" />
  865.  
  866.                             <p class="submit">
  867.                                 <input type="submit" name="Submit" value="<?php _e('Save Changes') ?>" />
  868.                             </p>
  869.                             </form>
  870.                            
  871.                             <h4><?php _e('Set default sort for individual categories'); ?></h4>
  872.                             <form method="post" action="">
  873.                             <table class="form-table">
  874.                                    <?php
  875.                                         $categories = $this->ss_multicontext_sort_options("categories");
  876.                                         foreach ($categories as $cat) {
  877.                                             $cat_html .= "<tr valign='top'><th scope='row'>". $cat['name'] . "</th><td>";
  878.                                             $cat_html .= $this->ss_make_admin_sort_select('ss_default_cat_sort_'.$cat['id'], $cat['sort']);
  879.                                             $cat_html .= "</td></tr>";                                
  880.                                         }
  881.                                         echo $cat_html;
  882.                                    ?>
  883.                             </table>
  884.                             <input type="hidden" name="action" value="categories-update" />
  885.                             <p class="submit">
  886.                                 <input type="submit" name="Submit" value="<?php _e('Save Changes') ?>" />
  887.                             </p>
  888.                             </form>
  889.                         </div>
  890.                     </div>                                
  891.                 </div>
  892.                 </p>
  893.             </div><?php
  894.     }
  895.  
  896.     function ss_where($where){
  897.         global $wpdb, $wp_query;
  898.        
  899.         $ssort = $this->ss_open_ssort();
  900.        
  901.         if ( ($ssort['ismeta'] === true) AND (is_tag() OR is_category() OR is_author() OR is_date() OR is_home() ) ) {
  902.             $where = $where ." AND ". $wpdb->postmeta.".meta_key = '".$ssort['fieldkey']."' ";
  903.         }
  904.         return $where;
  905.     }
  906. }
  907.  
  908.  
  909. /*
  910. ALL the ACTIONS / FILTERS / HOOKS
  911. */
  912.  
  913. $wpss = new WP_Smart_Sort();
  914.  
  915. add_action('admin_menu',    array($wpss, 'ss_add_pages'));
  916. add_filter('posts_orderby', array($wpss, 'ss_orderby'));
  917. add_filter('posts_where',   array($wpss, 'ss_where'));
  918. add_filter('posts_join',    array($wpss, 'ss_join'));
  919. add_action('init',          array($wpss, 'ss_init'));
  920.  
  921. add_action('plugins_loaded',         array($wpss, 'ss_plugins_loaded'));
  922. add_filter('query_vars',             array($wpss, 'ss_insert_my_rewrite_query_vars'));
  923. add_filter('generate_rewrite_rules', array($wpss, 'ss_rewrite'));
  924.  
  925. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement