Ankündigung

Einklappen
Keine Ankündigung bisher.

autofocus & value

Einklappen

Neue Werbung 2019

Einklappen
X
  • Filter
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge

  • autofocus & value

    Hallo Leute,

    ich habe mit einem Suchplugin (WP Custom Field Search) unter Wordpress eine tolle Suche realisiert. Jedoch gibt es noch Punkte die mich stören, ich hoffe ihr könnt mir dabei helfen. Mein PHP ist wirklich äußerst eingeschränkt und ich denke ohne geht es hier nicht weiter...

    Hier ein Codefile vom Plugin:

    PHP-Code:
    <?php if($title && !(@$params['noTitle'])){
        echo 
    $params['before_title'].$title.$params['after_title'];
    }
    ?>
        <form method='get' class='<?php echo $formCssClass?>' action='<?php echo $formAction?>'>
    <?php echo $hidden ?>
            <div class='searchform-params'>
    <?php        foreach($inputs as $input){?>
    <div class='<?php echo $input->getCSSClass()?>'><?php echo $input->getInput()?> </div>
    <?php        }?>
    </div>
    <div class='searchform-controls'>

    <input type='submit' name='search' value='<?php _e('Suchen','wp-custom-fields-search')?>'/>
    </div>
    <?php if(array_key_exists('showlink',$config) && $config['showlink']) { ?>
    <div class='searchform-spoiler'><?php echo $spoiler_link?></div>
    <?php ?>
    </form>

    Meine Probleme:

    Wie schaffe ich es, das ich hier einen autofocus integriere? Also das der Cursor beim aufrufen der Homepage in der Suchzeile blinkt.

    Gerne hätte ich auch Text in der Suchzeile. Also value="mein Text in der Zeile"...

    Habe schon herumprobiert aber leider ohne Erfolg. Ich hoffe ihr könnt mir helfen.

    lg Jason


  • #2
    Wenn du HTML 5 als Doctype verwendest, kannst du dem Feld doch einfach autofocus hinzufügen, funktioniert allerdings mal wieder nicht im IE <= 9. Alternativ kann man das dann noch über Javascript realisieren.

    Hier ist ein ganz netter Artikel dazu: HTML5 Autofocus Explained

    Kommentar


    • #3
      Doctype ist html 5.

      Aber die Frage ist wo schreibe ich autofocus in den php Code?

      Hier ist noch mehr Code vom Plugin.

      PHP-Code:
      <?php
      /*
      Plugin Name: WP Custom Search
      Plugin URI: http://www.webhammer.co.uk/bespoke-wordpress-plugins/wp-custom-search
      Description: Allows admin to build custom search form.  Allows the site admin to configure multiple html inputs for different fields including custom fields.  Also provides an extensible mechanism for integrating with other plugins data structures.
      Version: 0.3.26
      Author: Don Benjamin
      Author URI: http://www.webhammer.co.uk/
      Text Domain: wp-custom-fields-search
      */
      /*
       * Copyright 2009-2013 Don Benjamin
       * Licensed under the Apache License, Version 2.0 (the "License"); 
       * you may not use this file except in compliance with the License. 
       * You may obtain a copy of the License at 
       *
       *     http://www.apache.org/licenses/LICENSE-2.0 
       *
       * Unless required by applicable law or agreed to in writing, software
       * distributed under the License is distributed on an "AS IS" BASIS, 
       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
       * See the License for the specific language governing permissions and 
       * limitations under the License.
       */
          
      require_once(dirname(__FILE__).'/extra_search_fields.php');

          
      //Add Widget for configurable search.
          
      add_action('plugins_loaded',array('DB_CustomSearch_Widget','init'));


          class 
      DB_CustomSearch_Widget extends DB_Search_Widget {
              function 
      DB_CustomSearch_Widget($params=array()){
                  
      DB_CustomSearch_Widget::__construct($params);
              }
              function 
      __construct($params=array()){
                  
      $this->loadTranslations();
                  
      parent::__construct(__('Custom Fields ','wp-custom-fields-search'),$params);
                  
      add_action('admin_print_scripts', array(&$this,'print_admin_scripts'), 90);
                  
      add_action('admin_menu', array(&$this,'plugin_menu'), 90);
                  
      add_filter('the_content', array(&$this,'process_tag'),9);
                  
      add_shortcode'wp-custom-fields-search', array(&$this,'process_shortcode') );
                  
      wp_enqueue_script('jquery');
                  
      wp_enqueue_script('jquery-ui');
                  
      wp_enqueue_script('jquery-ui-autocomplete');
                  
      wp_enqueue_script('jquery-ui-sortable');
                  if(
      version_compare("2.7",$GLOBALS['wp_version'])>0wp_enqueue_script('dimensions');
              }
              function 
      init(){
                  global 
      $CustomSearchFieldStatic;
                  
      $CustomSearchFieldStatic['Object'] = new DB_CustomSearch_Widget();
                  
      $CustomSearchFieldStatic['Object']->ensureUpToDate();
              }

              function 
      currentVersion(){
                  return 
      "0.3.26";
              }

              function 
      ensureUpToDate(){
                  
      $version $this->getConfig('version');
                  
      $latest $this->currentVersion();
                  if(
      $version<$latest$this->upgrade($version,$latest);
              }

              function 
      upgrade($current,$target){
                  
      $options $this->getConfig();
                  if(
      version_compare($current,"0.3")<0){
                      
      $config $this->getDefaultConfig();
                      
      $config['name'] = __('Default Preset','wp-custom-fields-search');
                      
      $options['preset-default'] = $config;
                  }
                  
      $options['version']=$target;
                  
      update_option($this->id,$options);
              }

              function 
      getInputs($params false,$visitedPresets=array()){
                  if(
      is_array($params)){
                      
      $id $params['widget_id'];
                  } else {
                      
      $id $params;
                  }
                  if(@
      $visitedPresets[$id]) return array();
                  
      $visitedPresets[$id]=true;
                  
                  global 
      $CustomSearchFieldStatic;
                  if(!@
      $CustomSearchFieldStatic['Inputs'][$id]){
                      
      $classes $this->getClasses('joiner');
                  
                      
      $config $this->getConfig($id);
                      
      $inputs = array();
                      if(
      $config['preset']) $inputs $this->getInputs($config['preset'],$visitedPresets);
                      
      $nonFields $this->getNonInputFields();
                      if(
      $config)
                      foreach(
      $config as $k=>$v){
                          if(
      in_array($k,$nonFields)) continue;
                          if(!(
      class_exists($v['input']) && class_exists($v['comparison']) && class_exists($v['joiner']))) {
                              continue;
                          }
                          
      $inputs[] =  new CustomSearchField($v);

                      }
                      foreach(
      $inputs as $k=>$v){
                          
      $inputs[$k]->setIndex($k);
                      }
                      
      $CustomSearchFieldStatic['Inputs'][$id]=$inputs;
                  }
                  return 
      $CustomSearchFieldStatic['Inputs'][$id];
              }
              function 
      getTitle($params){
                  
      $config $this->getConfig($params['widget_id']);
                  return 
      $config['name'];
              }

              function 
      form_processPost($post,$old){
                  unset(
      $post['###TEMPLATE_ID###']);
                  if(!
      $post$post=array('exists'=>1);
                  
      $post stripslashes_deep($post);
                  return 
      $post;
              }
              function 
      getDefaultConfig(){
                  return 
      apply_filters('custom_search_default_config',
                  array(
      'name'=>'Site Search'
                      
      1=>array(
                          
      'label'=>__('Key Words','wp-custom-fields-search'),
                          
      'input'=>'TextField',
                          
      'comparison'=>'WordsLikeComparison',
                          
      'joiner'=>'PostDataJoiner',
                          
      'name'=>'all'
                      
      ),
                      
      2=>array(
                          
      'label'=>__('Category','wp-custom-fields-search'),
                          
      'input'=>'DropDownField',
                          
      'comparison'=>'EqualComparison',
                          
      'joiner'=>'CategoryJoiner'
                      
      ),
                  ));
              }
              function 
      form_outputForm($values,$pref){
                  
      $defaults=$this->getDefaultConfig();
                  
      $prefId preg_replace('/^.*\[([^]]*)\]$/','\\1',$pref);
                  
      $this->form_existsInput($pref);
                  
      $rand rand();
      ?>
          <div id='config-template-<?php echo $prefId?>' style='display: none;'>
          <?php 
              $templateDefaults 
      $defaults[1];
              
      $templateDefaults['label'] = 'Field ###TEMPLATE_ID###';
              echo  
      $this->singleFieldHTML($pref,'###TEMPLATE_ID###',$templateDefaults);
          
      ?>
          </div>

      <?php
                  
      foreach($this->getClasses('input') as $class=>$desc) {
                      if(
      class_exists($class))
                          
      $form = new $class();
                      else 
      $form false;
                      if(
      compat_method_exists($form,'getConfigForm')){
                          if(
      $form $form->getConfigForm($pref.'[###TEMPLATE_ID###]',array('name'=>'###TEMPLATE_NAME###'))){
      ?>
          <div id='config-input-templates-<?php echo $class?>-<?php echo $prefId?>' style='display: none;'>
              <?php echo $form?>
          </div>
              
      <?php                    }
                      }
                  }
       
      ?>
          <div id='config-form-<?php echo $prefId?>'>
      <?php
                  
      if(!$values$values $defaults;
                  
      $maxId=0;
                  
      $presets $this->getPresets();
                  
      array_unshift($presets,__('NONE','wp-custom-fields-search'));
      ?>
              <div class='searchform-name-wrapper'><label for='<?php echo $prefId?>[name]'><?php echo __('Search Title','wp-custom-fields-search')?></label><input type='text' class='form-title-input' id='<?php echo $prefId?>[name]' name='<?php echo $pref?>[name]' value='<?php echo @$values['name']?>'/></div>
              <div class='searchform-preset-wrapper'><label for='<?php echo $prefId?>[preset]'><?php echo __('Use Preset','wp-custom-fields-search')?></label>
      <?php
                  $dd 
      = new AdminDropDown($pref."[preset]",@$values['preset'],$presets);
                  echo 
      $dd->getInput()."</div>";
      ?>
          <div class='searchform-link-wrapper'>
              <input type='checkbox' id='<?php echo $pref?>[showlink]'
               name='<?php echo $pref?>[showlink]' <?php if(@$values['showlink']) { ?>checked='checked'<?php ?> />
              <label for='<?php echo $pref?>[showlink]'><?php echo __('Support plugin by including link to author\'s site','wp-custom-fields-search')?></label>
          </div>
          <div class='searchform-fields-wrapper sort-wrapper'>
      <?php
                  $nonFields 
      $this->getNonInputFields();
                  foreach(
      $values as $id => $val){
                      
      $maxId max($id,$maxId);
                      if(
      in_array($id,$nonFields)) continue;
                      echo 
      "<div id='config-form-$prefId-$id' class='sort-element'>".$this->singleFieldHTML($pref,$id,$val)."</div>";
                  }
      ?>
          </div>
          </div>

          <br/><a href='#' onClick="return CustomSearch.get('<?php echo $prefId?>').add();"><?php echo __('Add Field','wp-custom-fields-search')?></a>
          <script type='text/javascript'>
              jQuery(function(){
                  CustomSearch.create('<?php echo $prefId?>','<?php echo $maxId?>');
      <?php
          
      foreach($this->getClasses('joiner') as $joinerClass=>$desc){
              if(
      compat_method_exists($joinerClass,'getSuggestedFields')){
                  
      $options = eval("return $joinerClass::getSuggestedFields();");
                  
      $str '';
                  if(
      is_array($options)){
                      foreach(
      $options as $i=>$v){
                          
      $k=$i;
                          if(
      is_numeric($k)) $k=$v;
                          
      $options[$i] = json_encode(array('id'=>$k,'name'=>$v));
                      }
                      
      $str '['.join(',',$options).']';
                  } elseif(
      is_string($options)) {
                      
      $str json_encode($options);
                  }
                  echo 
      "CustomSearch.setOptionsFor('$joinerClass',".$str.");\n";
              }elseif(eval(
      "return $joinerClass::needsField();")){
                  echo 
      "CustomSearch.setOptionsFor('$joinerClass','any');\n";
              }
          }
      ?>
          });
          </script>
      <?php
              
      }

              function 
      getNonInputFields(){
                  return array(
      'exists','name','preset','version','order','template','showlink');
              }
              function 
      singleFieldHTML($pref,$id,$values){
                  
      $prefId preg_replace('/^.*\[([^]]*)\]$/','\\1',$pref);
                  
      $pref $pref."[$id]";
                  
      $htmlId $pref."[exists]";
                  
      $output "<input type='hidden' name='$htmlId' value='1'/>";
                  
      $titles="<th>".__('Label','wp-custom-fields-search')."</th>";
                  
      $inputs="<td><input type='text' name='$pref"."[label]' value='$values[label]' class='form-field-title'/></td><td><a href='#' onClick='return CustomSearch.get(\"$prefId\").toggleOptions(\"$id\");'>".__('Show/Hide Config','wp-custom-fields-search')."</a></td>";
                  
      $output.="<table class='form-field-table'><tr>$titles</tr><tr>$inputs</tr></table>";
                  
      $output.="<div id='form-field-advancedoptions-$prefId-$id' style='display: none'>";
                  
      $inputs='';$titles='';
                  
      $titles="<th>".__('Data Field','wp-custom-fields-search')."</th>";
                  
      $inputs="<td><div id='form-field-dbname-$prefId-$id' class='form-field-title-div'><input type='text' name='$pref"."[name]' value='".@$values["name"]."' class='form-field-title'/></div></td>";
                  
      $count=1;
                  foreach(array(
      'joiner'=>__('Data Type','wp-custom-fields-search'),'comparison'=>__('Compare','wp-custom-fields-search'),'input'=>__('Widget','wp-custom-fields-search')) as $k=>$v){
                      
      $dd = new AdminDropDown($pref."[$k]",$values[$k],$this->getClasses($k),array('onChange'=>'CustomSearch.get("'.$prefId.'").updateOptions("'.$id.'","'.$k.'")','css_class'=>"wpcfs-$k"));
                      
      $titles="<th>".$v."</th>".$titles;
                      
      $inputs="<td>".$dd->getInput()."</td>".$inputs;
                      if(++
      $count==2){
                          
      $output.="<table class='form-field-table form-class-$k'><tr>$titles</tr><tr>$inputs</tr></table>";
                          
      $count=0;
                          
      $inputs $titles='';
                      }
                  }
                  if(
      $titles){
                      
      $output.="<table class='form-field-table'><tr>$titles</tr><tr>$inputs</tr></table>";
                      
      $inputs $titles='';
                  }
                  
      $titles.="<th>".__('Numeric','wp-custom-fields-search')."</th><th>".__('Widget Config','wp-custom-fields-search')."</th>";
                  
      $inputs.="<td><input type='checkbox' ".(@$values['numeric']?"checked='true'":"")." name='$pref"."[numeric]'/></td>";

                  
      $widgetConfig='';
                  if(
      class_exists($widgetClass $values['input'])){
                      
      $widget = new $widgetClass();
                      if(
      compat_method_exists($widget,'getConfigForm'))
                          
      $widgetConfig=$widget->getConfigForm($pref,$values);
                  }


                  
      $inputs.="<td><div id='$this->id"."-$prefId"."-$id"."-widget-config'>$widgetConfig</div></td>";
                  
      $output.="<table class='form-field-table'><tr>$titles</tr><tr>$inputs</tr></table>";
                  
      $output.="</div>";
                  
      $output.="<a href='#' onClick=\"return CustomSearch.get('$prefId').remove('$id');\">Remove Field</a>";
                  return 
      "<div class='field-wrapper'>$output</div>";
              }

              function 
      getRootURL(){
                  return 
      WP_CONTENT_URL .'/plugins/' .  dirname(plugin_basename(__FILE__) ) . '/';
              }
              function 
      print_admin_scripts($params){
                  
      $jsRoot $this->getRootURL().'js';
                  
      $cssRoot $this->getRootURL().'css';
                  
      $scripts = array('Class.js','CustomSearch.js');
                  foreach(
      $scripts as $file){
                      echo 
      "<script src='$jsRoot/$file' ></script>";
                  }
                  echo 
      "<link rel='stylesheet' href='$cssRoot/admin.css' >";
              }

              function 
      getJoiners(){
                  return 
      $this->getClasses('joiner');
              }
              function 
      getComparisons(){
                  return 
      $this->getClasses('comparison');
              }
              function 
      getInputTypes(){
                  return 
      $this->getClasses('input');
              }
              function 
      getClasses($type){
                  global 
      $CustomSearchFieldStatic;
                  if(!
      $CustomSearchFieldStatic['Types']){
                      
      $CustomSearchFieldStatic['Types'] = array(
                          
      "joiner"=>array(
                              
      "PostDataJoiner" =>__"Post Field",'wp-custom-fields-search'),
                              
      "CustomFieldJoiner" =>__"Custom Field",'wp-custom-fields-search'),
                              
      "CategoryJoiner" =>__"Category",'wp-custom-fields-search'),
                              
      "TagJoiner" =>__"Tag",'wp-custom-fields-search'),
                              
      "PostTypeJoiner" =>__"Post Type",'wp-custom-fields-search'),
                          ),
                          
      "input"=>array(
                              
      "TextField" =>__"Text Input",'wp-custom-fields-search'),
                              
      "DropDownField" =>__"Drop Down",'wp-custom-fields-search'),
                              
      "RadioButtonField" =>__"Radio Button",'wp-custom-fields-search'),
                              
      "HiddenField" =>__"Hidden Constant",'wp-custom-fields-search'),
                          ),
                          
      "comparison"=>array(
                              
      "EqualComparison" =>__"Equals",'wp-custom-fields-search'),
                              
      "LikeComparison" =>__"Phrase In",'wp-custom-fields-search'),
                              
      "WordsLikeComparison" =>__"Words In",'wp-custom-fields-search'),
                              
      "LessThanComparison" =>__"Less Than",'wp-custom-fields-search'),
                              
      "MoreThanComparison" =>__"More Than",'wp-custom-fields-search'),
                              
      "AtMostComparison" =>__"At Most",'wp-custom-fields-search'),
                              
      "AtLeastComparison" =>__"At Least",'wp-custom-fields-search'),
                              
      "RangeComparison" =>__"Range",'wp-custom-fields-search'),
      //TODO: Make this work...
      //                        "NotEqualComparison" =>__( "Not Equal To",'wp-custom-fields-search'),
                          
      )
                      );
                      
      $CustomSearchFieldStatic['Types'] = apply_filters('custom_search_get_classes',$CustomSearchFieldStatic['Types']);
                  }
                  return 
      $CustomSearchFieldStatic['Types'][$type];
              }
              function 
      plugin_menu(){
                  
      add_options_page('Form Presets','WP Custom Fields Search',8,__FILE__,array(&$this,'presets_form'));
              }
              function 
      getPresets(){
                  
      $presets = array();
                  foreach(
      array_keys($config $this->getConfig()) as $key){
                      if(
      strpos($key,'preset-')===0) {
                          
      $presets[$key] = $key;
                          if(
      $name $config[$key]['name'])
                              
      $presets[$key]=$name;
                      }
                  }
                  return 
      $presets;
              }
              function 
      presets_form(){
                  
      $presets=$this->getPresets();
                  if(!
      $preset = @$_REQUEST['selected-preset']){
                      
      $preset 'preset-default';
                  }
                  if(!
      $presets[$preset]){
                      
      $defaults $this->getDefaultConfig();
                      
      $options $this->getConfig();
                      
      $options[$preset] = $defaults;
                      if(
      $n $_POST[$this->id][$preset]['name'])
                          
      $options[$preset]['name'] = $n;
                      elseif(
      $preset=='preset-default')
                          
      $options[$preset]['name'] = 'Default';
                      else{
                          list(
      $junk,$id) = explode("-",$preset);
                          
      $options[$preset]['name'] = 'New Preset '.$id;
                      }
                      
      update_option($this->id,$options);
                      
      $presets[$preset] = $options[$preset]['name'];
                  }
                  if(@
      $_POST['delete']){
                      
      check_admin_referer($this->id.'-editpreset-'.$preset);
                      
      $options $this->getConfig();
                      unset(
      $options[$preset]);
                      unset(
      $presets[$preset]);
                      
      update_option($this->id,$options);
                      list(
      $preset,$name) = each($presets);
                  }

                  
      $index 1;
                  while(@
      $presets["preset-$index"]) $index++;
                  
      $presets["preset-$index"] = __('New Preset','wp-custom-fields-search');

                  
      $linkBase $_SERVER['REQUEST_URI'];
                  
      $linkBase preg_replace("/&?selected-preset=[^&]*(&|$)/",'',$linkBase);
                  foreach(
      $presets as $key=>$name){
                      
      $config $this->getConfig($key);
                      if(
      $config && $config['name']) $name=$config['name'];
                      if((
      $n = @$_POST[$this->id][$key]['name'])&&(!@$_POST['delete']))
                          
      $name $n;
                      
      $presets[$key]=$name;
                  }
                  
      $plugin=&$this;
                  
      ob_start();
                  
      wp_nonce_field($this->id.'-editpreset-'.$preset);
                  
      $hidden ob_get_contents();
                  
      $hidden.="<input type='hidden' name='selected-preset' value='$preset'>";
                  
      $shouldSave $_POST['selected-preset'] && !$_POST['delete'] && check_admin_referer($this->id.'-editpreset-'.$preset);
                  
      ob_end_clean();
                  include(
      dirname(__FILE__).'/templates/options.php');
              }
              function 
      process_tag($content){
                  
      $regex '/\[\s*wp-custom-fields-search\s+(?:([^\]=]+(?:\s+.*)?))?\]/';
                  return 
      preg_replace_callback($regex, array(&$this'generate_from_tag'), $content);
              }
              function 
      process_shortcode($atts,$content){
                  return 
      $this->generate_from_tag(array("",$atts['preset']));
              }
              function 
      generate_from_tag($reMatches){
                  global 
      $CustomSearchFieldStatic;
                  
      ob_start();

                  
      $preset=$reMatches[1];
                  if(!
      $preset$preset 'default';
                  
      wp_custom_fields_search($preset);

                  
      $form ob_get_contents();
                  
      ob_end_clean();
                  return 
      $form;
              }
          }
          global 
      $CustomSearchFieldStatic;
          
      $CustomSearchFieldStatic['Inputs'] = array();
          
      $CustomSearchFieldStatic['Types'] = array();

          class 
      AdminDropDown extends DropDownField {
              function 
      AdminDropDown($name,$value,$options,$params=array()){
                  
      AdminDropDown::__construct($name,$value,$options,$params);
              }
              function 
      __construct($name,$value,$options,$params=array()){
                  
      $params['options'] = $options;
                  
      $params['id'] = @$params['name'];
                  
      parent::__construct($params);
                  
      $this->name $name;
                  
      $this->value $value;
              }
              function 
      getHTMLName(){
                  return 
      $this->name;
              }
              function 
      getValue(){
                  return 
      $this->value;
              }
              function 
      getInput(){
                  return 
      parent::getInput($this->name,null);
              }
          }

      if (!
      function_exists('json_encode'))
      {
        function 
      json_encode($a=false)
        {
          if (
      is_null($a)) return 'null';
          if (
      $a === false) return 'false';
          if (
      $a === true) return 'true';
          if (
      is_scalar($a))
          {
            if (
      is_float($a))
            {
              
      // Always use "." for floats.
              
      return floatval(str_replace(",""."strval($a)));
            }

            if (
      is_string($a))
            {
              static 
      $jsonReplaces = array(array("\\""/""\n""\t""\r""\b""\f"'"'), array('\\\\''\\/''\\n''\\t''\\r''\\b''\\f''\"'));
              return 
      '"' str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
            }
            else
              return 
      $a;
          }
          
      $isList true;
          for (
      $i 0reset($a); $i count($a); $i++, next($a))
          {
            if (
      key($a) !== $i)
            {
              
      $isList false;
              break;
            }
          }
          
      $result = array();
          if (
      $isList)
          {
            foreach (
      $a as $v$result[] = json_encode($v);
            return 
      '[' join(','$result) . ']';
          }
          else
          {
            foreach (
      $a as $k => $v$result[] = json_encode($k).':'.json_encode($v);
            return 
      '{' join(','$result) . '}';
          }
        }
      }
      function 
      wp_custom_fields_search($presetName='default'){
          global 
      $CustomSearchFieldStatic;
          if(
      strpos($presetName,'preset-')!==0$presetName="preset-$presetName";
          
      $CustomSearchFieldStatic['Object']->renderWidget(array('widget_id'=>$presetName,'noTitle'=>true),array('number'=>$presetName));
      }
      function 
      compat_method_exists($class,$method){
          return 
      method_exists($class,$method) || in_array(strtolower($method),get_class_methods($class));
      }

      Kommentar


      • #4
        Na du musst einfach in den entsprechenden <input>-Tag autofocus schreiben. Weiß ja nicht, wo du es möchtest, aber ein Beispiel wäre:

        PHP-Code:
        <input type='text' class='form-title-input' id='<?php echo $prefId?>[name]' name='<?php echo $pref?>[name]' value='<?php echo @$values['name']?>' autofocus/>

        Kommentar


        • #5
          Habs hinbekommen. Da war noch eine php Datei wo es reingehört hat.


          PHP-Code:
          <?php
          /*
           * Copyright 2009-2013 Don Benjamin
           * Licensed under the Apache License, Version 2.0 (the "License"); 
           * you may not use this file except in compliance with the License. 
           * You may obtain a copy of the License at 
           *
           *     http://www.apache.org/licenses/LICENSE-2.0 
           *
           * Unless required by applicable law or agreed to in writing, software
           * distributed under the License is distributed on an "AS IS" BASIS, 
           * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
           * See the License for the specific language governing permissions and 
           * limitations under the License.
           */

          /*
           *  This library is required for the configurable search plugin.
           *
           *  It could also be used to make static unconfigurable search plugins.
           *
           * Author: Don Benjamin
           * Author URI: http://don-benjamin.co.uk
           * */


          if ( !defined('WP_CONTENT_URL') )
              
          define'WP_CONTENT_URL'get_option('siteurl') . '/wp-content');
          if ( !
          defined('WP_CONTENT_DIR') )
              
          define'WP_CONTENT_DIR'ABSPATH 'wp-content' );

          class 
          ParameterisedObject {
              var 
          $params=array();
              function 
          ParameterisedObject($params=array()){
                  
          $this->__construct($params);
              }
              function 
          __construct($params=array()){
                  
          $this->setParams($params);
                  if(!
          is_array($this->params)){
                      foreach(
          debug_backtrace() as $trace){
                          
          extract($trace);
                          echo 
          "<li>$file:$line $class.$function</li>";
                      }
                      die(
          "<h1>".get_class($this)."</h1>");
                  }
              }

              function 
          setParams($params){
                  
          $this->params=$params;
              }

              function 
          param($key,$default=null){
                  if(!
          array_key_exists($key,$this->params)) return $default;
                  return 
          $this->params[$key];
              }
          }
          class 
          DB_WP_Widget extends ParameterisedObject {
              function 
          DB_WP_Widget($name,$params=array()){
                  
          DB_WP_Widget::__construct($name,$params);
              }
              function 
          __construct($name,$params=array()){
                  
          parent::__construct($params);
                  
          $this->name $name;
                  
          $this->id strtolower(get_class($this));
                  
          $options get_option($this->id);


          //        register_sidebar_widget($this->name,array(&$this,'renderWidget'));
                  
          $doesOwnConfig $this->param('doesOwnConfig',false);
                  
          $desc $this->param('description',$this->name);
                  
          $widget_ops = array('classname' => $this->id'description' => __($desc));
                  
          $control_ops = array('width' => 400'height' => 350'id_base' => $this->id);
                  
          $name $this->name;
              
                  
          $id false;
                  do {
                      if(
          $options)
                      foreach ( 
          array_keys($options) as $o ) {
                          
          // Old widgets can have null values for some reason
                          
          if ( !isset($options[$o]['exists']) )
                              continue;
                          
          $id "$this->id-".abs($o); // Never never never translate an id
                          
          wp_register_sidebar_widget($id$name, array(&$this,'renderWidget'), $widget_ops, array( 'number' => $o ));
                          
          wp_register_widget_control($id$name, array(&$this,'configForm'), $control_ops, array( 'number' => $o ));
                      }
                      
          $options = array( -1=>array('exists'=>1));
                  } while(!
          $id);
              }

              function 
          setParams($params){
                  
          parent::setParams($this->overrideParams($params));
              }

              function 
          getDefaults(){
                  return array(
          'doesOwnConfig'=>false);
              }
              function 
          overrideParams($params){
                  foreach(
          $this->getDefaults() as $k=>$v){
                      if(!
          array_key_exists($k,$params)) $params[$k] = $v;
                  }
                  return 
          $params;
              }

              function 
          renderWidget(){
                  echo 
          "<h1>Unconfigured Widget</h1>";
              }

              function 
          defaultWidgetConfig(){
                  return array(
          'exists'=>'1');
              }
              function 
          getConfig($id=null,$key=null){
                  
          $options get_option($this->id);
                  if(
          is_null($id)) return $options;
                  if(!@
          array_key_exists($id,$options))
                      
          $id preg_replace('/^.*-(\d+)$/','\\1',$id);
                  if(
          is_null($key))
                      return @
          $options[$id];
                  else 
                      return @
          $options[$id][$key];
              }
              function 
          configForm($args,$force=false){
                  static 
          $first;
                  global 
          $wp_registered_widgets;

                  if ( !
          is_array($args) )
                      
          $args = array( 'number' => $args );

                  
          $args wp_parse_args($args,array('number'=>-1));
                  static 
          $updated = array();

                  
          $options get_option($this->id);

                  if(!@
          $updated[$this->id] && (@$_POST['sidebar'] || $force)){
                      
          $updated[$this->id]=true;
                      
          $sidebar = (string) $_POST['sidebar'];
                      
          $default_options=$this->defaultWidgetConfig();

                      
          $sidebars_widgets wp_get_sidebars_widgets();
                      if ( isset(
          $sidebars_widgets[$sidebar]) )
                          
          $this_sidebar $sidebars_widgets[$sidebar];
                      else
                          
          $this_sidebar = array();

                      foreach ( 
          $this_sidebar as $_widget_id ) {
                          
          $callback $wp_registered_widgets[$_widget_id]['callback'];
                             if(
          is_array($callback) && get_class($callback[0])==get_class($this) && isset($wp_registered_widgets[$_widget_id]['params'][0]['number']) ) {{
                                 
          $widget_number $wp_registered_widgets[$_widget_id]['params'][0]['number'];
                             }
                          if ( !
          in_array"$this->id-$widget_number"$_POST['widget-id'] ) ) 
                              unset(
          $options[$widget_number]);
                          }
                      }
                      foreach ((array)
          $_POST[$this->id] as $widget_number => $posted) {
                          if(!isset(
          $posted['exists']) && isset($options[$widget_number]))continue;

                          
          $widgetOptions $this->form_processPost($posted,$options[$widget_number]);
                          
          $options[$widget_number] = $widgetOptions;
                      }
                      
          update_option($this->id,$options);
                  }
                  global 
          $mycount;
                  if(-
          1==$args['number']){
                      
          $args['number']='%i%';
                      
          $values = @$default_options;
                  } else {
                      
          $values $options[$args['number']];
                  }
                  
          $this->form_outputForm($values,$this->id.'['.$args['number'].']');
              }
              function 
          form_processPost($post,$old){
                  return array(
          'exists'=>1);
              }
              function 
          form_outputForm($old,$pref){
                  
          $this->form_existsInput($pref);
              }
              function 
          form_existsInput($pref){
                  echo 
          "<input type='hidden' name='".$pref."[exists]' value='1'/>";
              }

              function 
          nameAsId(){
                  return 
          strtolower(str_replace(" ","_",$this->name));
              }
          }

          class 
          DB_Search_Widget extends DB_WP_Widget {
              var 
          $inputs = array();

              function 
          DB_Search_Widget($name){
                  
          DB_Search_Widget::__construct($name);
              }
              function 
          __construct($name='Custom',$params=array()){
                  
          $this->loadTranslations();
                  
          parent::__construct(sprintf(__('%1$s Search','wp-custom-fields-search'),$name),$params);
                  
          add_filter('posts_join',array(&$this,'join_meta'));
                  
          add_filter('posts_where',array(&$this,'sql_restrict'));
                  
          add_filter('posts_groupby', array(&$this,'sql_group'));
                  
          add_filter('posts_orderby', array(&$this,'sql_order'));
                  
          add_filter('home_template',array(&$this,'rewriteHome'));
                  
          add_filter('page_template',array(&$this,'rewriteHome'));
                  
          add_filter'get_search_query', array(&$this,'getSearchDescription'));
                  
          add_action('wp_head', array(&$this,'outputStylesheets'), 1);
                  
          add_action('pre_get_posts',array(&$this,'setSearchVar'));

                  
          /** These are for relevanssi compatibility */
                  
          add_filter('posts_request',array(&$this,'store_search'),9);
                  
          add_filter('posts_request',array(&$this,'restore_search'),11);
                  
          add_filter('the_posts',array(&$this,'store_search'),9);
                  
          add_filter('the_posts',array(&$this,'restore_search'),11);
              }
              function 
          loadTranslations(){
                  static 
          $loaded;
                  if ( !
          $loaded && function_exists('load_plugin_textdomain') ) {
                      
          $loaded=true;
                      if ( !
          defined('WP_PLUGIN_DIR') ) {
                          
          load_plugin_textdomain('wp-custom-fields-search'str_replaceABSPATH''dirname(__FILE__) ) );
                      } else {
                          
          load_plugin_textdomain('wp-custom-fields-search'falsedirnameplugin_basename(__FILE__) ) );
                      }
                  }
              }
              function 
          addInput($input){
                  
          $this->inputs[] = $input;
              }
              function 
          outputStylesheets(){
                  
          $dir WP_CONTENT_URL .'/plugins/' .  dirname(plugin_basename(__FILE__) ) . '/';
                  echo 
          "\n".'<style type="text/css" media="screen">@import "'$dir .'templates/searchforms.css";</style>'."\n";
              }
              function 
          setSearchVar($wpdb){
                  if(
          $this->isPosted()){
                      
          $wpdb->is_search=true;
                  }
              }

              function 
          getInputs($params){
                  return 
          $this->inputs;
              }

              function 
          getTitle(){
                  return 
          $this->param('description',$this->name);
              }

              function 
          renderWidget($params=array(),$p2 = array()){
                  
          $title $this->getTitle($params);
                  
          $inputs $this->getInputs($params);
                  
          $hidden "<input type='hidden' name='search-class' value='".$this->getPostIdentifier()."'/><input type='hidden' name='widget_number' value='".$p2['number']."'/>";
                  
          $formCssClass 'custom_search widget custom_search_'.$this->nameAsId();
                  
          $formAction get_option('home');
                  if(
          function_exists('locate_template'))
                      
          $formTemplate locate_template(array('wp-custom-fields-search-form.php'));
                  if(!
          $formTemplate$formTemplate dirname(__FILE__).'/templates/wp-custom-fields-search-form.php';

                  foreach(
          $inputs as $k=>$v){
                      if(
          $v->isHidden()){
                          
          $hidden.=$v->getInput(false);
                          unset(
          $inputs[$k]);
                      }
                  }
                  
          $host_name $_SERVER['HTTP_HOST'];
                  switch(
          substr(md5($host_name),0,1)){
                  case 
          'A':case 'B': case 'C': case 'D':
                      
          $spoiler_link "<a href='http://www.webhammer.co.uk/bespoke-wordpress-plugins' title='Web Hammer Wordpress Plugins'>Web Hammer Wordpress Plugins</a>";
                      break;
                  case 
          'E':case 'F':case '1': case '2':
                      
          $spoiler_link "<a href='http://www.webhammer.co.uk/bespoke-wordpress-plugins' title='Web Hammer Plugins & ECommerce'>Web Hammer Plugins & ECommerce</a>";
                      break;
                  case 
          '3': case '4': case '5': case '6':
                      
          $spoiler_link "<a href='http://www.webhammer.co.uk/bespoke-wordpress-plugins' title='Bespoke Plugins by Web Hammer'>Bespoke Plugins by Web Hammer</a>";
                      break;
                  case 
          '7': case '8': case '9': case '0': default:
                      
          $spoiler_link "<a href='http://www.webhammer.co.uk/bespoke-wordpress-plugins' title='Search Plugin by Web Hammer'>Search Plugin by Web Hammer</a>";
                      break;
                  }
                  
          $spoiler_link 
                      
          $spoiler_link apply_filters('wpcfs-spoiler',$spoiler_link);

                  
          $config $this->getConfig($p2['number']);
                  echo 
          $params['before_widget'];
                  include(
          $formTemplate);
                  echo 
          $params['after_widget'];
              }

              function 
          isPosted(){
                  return @
          $_GET['search-class'] == $this->getPostIdentifier();
              }
              function 
          getPostIdentifier(){
                  return 
          get_class($this).'-'.$this->id;
              }
              function 
          isHome($isHome){
                  return 
          $isHome && !$this->isPosted();
              }
              function 
          rewriteHome($homeTemplate){
                  if(
          $this->isPosted()) return get_query_template('search');
                  return 
          $homeTemplate;
              }

              function 
          join_meta($join){
                  if(
          $this->isPosted()){
                      
          $desc = array();
                      foreach(
          $this->getInputs($_REQUEST['widget_number']) as $input){
                          
          $join $input->join_meta($join);
                          
          $desc $input->describeSearch($desc);
                      }
                      if(
          $desc){
                          
          $desc join(__(" and ",'wp-custom-fields-search'),$desc);
                      } else {
                          
          $desc __("All Entries",'wp-custom-fields-search');
                      }
                      
          $this->desc=$desc;
                  }
                  return 
          $join;
              }

              function 
          getSearchDescription($desc){
                  if(
          $this->isPosted()) return $this->desc;
                  return 
          $desc;
              }
              function 
          sql_restrict($where){
                  if(
          $this->isPosted()){
                      global 
          $wpdb;
                      
          /** This could possibly be considered invasive, need to think this bit through
                       * properly.
                       */
                      
          $where preg_replace("_AND\s*\(ID\s*=\s*'\d+'\)_","",$where);
                      
          $where preg_replace("/AND $wpdb->posts.post_type = '(post|page)'/","",$where);
                      
          $where.= " AND ($wpdb->posts.post_type='post')";
                      foreach(
          $this->getInputs($_REQUEST['widget_number']) as $input){
                          
          $where $input->sql_restrict($where);
                      }
                  }
                  return 
          $where;
              }
              function 
          sql_group($group){
                  if(
          $this->isPosted()){
                      global 
          $wpdb;
                      
          $group "$wpdb->posts.ID";
                  }
                  return 
          $group;
              }
              function 
          sql_order($order){
                  if(
          $this->isPosted()){
                      foreach(
          $this->getInputs($_REQUEST['widget_number']) as $input){
                          
          $order $input->sql_order($order);
                      }
                  }
                  return 
          $order;
              }

              function 
          toSearchString(){
              }
              function 
          store_search($sql){
                  
          $this->sql $sql;
                  return 
          $sql;
              }
              function 
          restore_search($sql){
                  if(
          $this->isPosted()){
                      
          $sql $this->sql;
                  }
                  return 
          $sql;
              }
          }


          class 
          SearchFieldBase {
              function 
          SearchFieldBase(){
                  
          SearchFieldBase::__construct();
              }
              function 
          __construct(){
                  
          add_filter('search_params',array(&$this,'form_inputs'));
                  static 
          $index;
                  
          $this->index = ++$index;
               }
              function 
          form_inputs($form){
                  die(
          "Unimplemented function ".get_class($this).".".__FUNCTION__);
              }
              function 
          sql_restrict($where){
                  die(
          "Unimplemented function ".get_class($this).".".__FUNCTION__);
              }
          }

          class 
          Field extends ParameterisedObject {
              function 
          splitMultiValues($value){
                  return array(
          $value);
              }
              function 
          valueToDisplay($value,$name,$joiner){
                  return 
          $value;
              }
              function 
          getValue($name){
                  
          $v =  @$_REQUEST[$this->getHTMLName($name)];
                  if(
          get_magic_quotes_gpc() || function_exists('wp_magic_quotes')) $vstripslashes_deep($v);
                  return 
          $v;
              }

              function 
          getHTMLName($name){
                  return 
          'cs-'.str_replace(" ","_",$name);
              }

              function 
          getInput($name){
                  
          $htmlName $this->getHTMLName($name);
                  
          $value $this->getValue($name);
                  return 
          "<input name='$htmlName' value='$value' autofocus='autofocus' placeholder=' placeholder ...'/>";
              }
              function 
          getCSSClass(){
                  return 
          get_class($this);
              }
          }
          class 
          TextField extends Field {
          }
          class 
          TextInput extends TextField{}
          class 
          DropDownField extends Field {
              function 
          DropDownField($params=array()){
                  
          $this->__construct($params);
              }
              function 
          __construct($params = array()){
                  
          parent::__construct($params);
                  if(
          $optionString $this->param('dropdownoptions',false)){
                      
          $options=array();
                      
          $optionPairs explode(',',$optionString);
                      
          $prefix="";
                      foreach(
          $optionPairs as $option){
                          if(
          strrchr($option,"\\")=="\\"){
                              
          $prefix .= substr($option,0,-1).",";
                              continue;
                          }
                          
          $option $prefix.$option;
                          list(
          $k,$v) = explode(':',$option);
                          if(!
          $v$v=$k;
                          
          $options[$k]=$v;
                          
          $prefix "";
                      }
                  } else {
                      
          $options $this->param('options',array());
                  }
                  
          $this->options $options;
              }

              function 
          getOptions($joiner,$name){
                  if(
          $this->param('fromDb',!$this->options)){
                      
          $options = array(''=>__('alle','wp-custom-fields-search'));
                      
          $auto $joiner->getAllOptions($name);
                      
          asort($auto);
                      
          $options +=$auto;
                      return 
          $options;
                  } else {
                      return 
          $this->options;
                  }
              }
              function 
          valueToDisplay($value,$name,$joiner){
                  
          $options $this->getOptions($joiner,$name);
                  return 
          $options[$value];
              }
              function 
          getInput($name,$joiner,$fieldName=null){
                  if(!
          $fieldName$fieldName=$name;
                  
          $v $this->getValue($name);
                  
          $id $this->getHTMLName($name);

                  
          $options '';
                  foreach(
          $this->getOptions($joiner,$fieldName) as $option=>$label){
                      
          $checked = (($option==$v)||($label==$v))?" selected='selected'":"";
                      
          $option htmlspecialchars($option,ENT_QUOTES);
                      
          $label htmlspecialchars($label,ENT_QUOTES);
                      
          $options.="<option value='$option'$checked>$label</option>";
                  }
                  
          $atts '';
                  if(@
          $this->params['onChange']) $atts ' onChange="'.htmlspecialchars($this->params['onChange']).'"';
                  if(@
          $this->params['id']) $atts .= ' id="'.htmlspecialchars($this->params['id']).'"';
                  if(@
          $this->params['css_class']) $atts .= ' class="'.htmlspecialchars($this->params['css_class']).'"';
                  return 
          "<select name='$id$atts>$options</select>";
              }
              function 
          getConfigForm($id,$values){
                  return 
          "<label for='$id-dropdown-options'>".__('Drop Down Options','wp-custom-fields-search')."</label><input id='$id-dropdown-options' name='$id"."[dropdownoptions]' value='".@$values["dropdownoptions"]."'/>";
              }
          }
          class 
          HiddenField extends Field {
              function 
          HiddenField(){
                  
          $func_args func_get_args();
                  
          call_user_func_array(array($this,'__construct'),$func_args);
              }
              function 
          __construct($params = array()){
                  
          $params['hidden']=true;
                  
          parent::__construct($params);
              }
              function 
          getValue(){
                  return 
          $this->param('constant-value',null);
              }

              function 
          getInput($name){
                  
          $v=$this->getValue($name);
                  
          $id $this->getHTMLName($name);
                  return 
          "<input type='hidden' name='".htmlspecialchars($name)."' value='".htmlspecialchars($v)."'/>";
              }
              function 
          getConfigForm($id,$values){
                  return 
          "<label for='$id-constant-value'>".__('Constant Value','wp-custom-fields-search')."</label><input id='$id-constant-value' name='$id"."[constant-value]' value='".@$values['constant-value']."'/>";
              }
              function 
          valueToDisplay($value,$name,$joiner){
                  return 
          null;
              }
          }

          /* TODO: Add Caching */
          class CustomFieldReader {

          }

          class 
          DropDownFromValues extends DropDownField {
              function 
          DropDownFromValues($params=array()){
                  
          $this->__construct($params);
              }

              function 
          __construct($params=array()){
                  
          $params['fromDb'] = true;
                  
          parent::__construct(array(),$params);
              }

              function 
          getConfigForm($id,$values){
                  return 
          "";
              }
          }
          class 
          RadioButtonField extends Field {
              function 
          RadioButtonField($options=array(),$params=array()){
                  
          RadioButtonField::__construct($options,$params);
              }
              function 
          __construct($params=array()){
                  
          parent::__construct($params);
                  
          $options null;
                  if(@
          $params['radiobuttonoptions']){
                      
          $options=array();
                      
          $optionPairs explode(',',@$params['radiobuttonoptions']);
                      foreach(
          $optionPairs as $option){
                          list(
          $k,$v) = explode(':',$option);
                          if(!
          $v$v=$k;
                          
          $options[$k]=$v;
                      }
                  }
                  
          $this->options $options;
              }
              function 
          getOptions($joiner,$name){
                  if(
          $this->param('fromDb',!$this->options)){
                      return 
          $joiner->getAllOptions($name);
                  } else {
                      return 
          $this->options;
                  }
              }
              function 
          getInput($name,$joiner,$fieldName=null){
                  if(!
          $fieldName$fieldName=$name;
                  
          $v $this->getValue($name);
                  
          $id $this->getHTMLName($name);

                  
          $options '';
                  foreach(
          $this->getOptions($joiner,$fieldName) as $option=>$label){
                      
          $option htmlspecialchars($option,ENT_QUOTES);
                      
          $label htmlspecialchars($label,ENT_QUOTES);
                      
          $checked = ($option==$v)?" checked='true'":"";
                      
          $htmlId "$id-$option";

                      
          $options.="<div class='radio-button-wrapper'><input type='radio' name='$id' id='$htmlId' value='$option'$checked> <label for='$htmlId'>$label</label></div>";
                  }
                  return 
          $options;
              }
              function 
          getCSSClass(){
                  return 
          "RadioButton";
              }
              function 
          getConfigForm($id,$values){
                  return 
          "<label for='$id-radiobutton-options'>Radio Button Options</label><input id='$id-radiobutton-options' name='$id"."[radiobuttonoptions]' value='".@$values["radiobuttonoptions"]."'/>";
              }
          }
          class 
          RadioButtonFromValues extends RadioButtonField {
              function 
          RadioButtonFromValues($fieldName=null){
                  
          RadioButtonFromValues::__construct($fieldName);
              }

              function 
          __construct($fieldName=null,$params){
                  
          $params['fromDb'] = true;
                  
          parent::__construct($options,$params);
              }
              function 
          getConfigForm($id,$values){
                  return 
          "";
              }
          }

          class 
          Comparison {
              function 
          addSQLWhere($field,$value){
                  die(
          "Unimplemented function ".get_class($this).".".__FUNCTION__);
              }
              function 
          describeSearch($value){
                  die(
          "Unimplemented function ".get_class($this).".".__FUNCTION__);
              }
              function 
          sql_order($order){
                  return 
          $order;
              }
              function 
          shouldJoin($value){
                  return 
          $value;
              }
          }
          class 
          EqualComparison extends Comparison {
              function 
          addSQLWhere($field,$value){
                  return 
          "$field = '$value'";
              }
              function 
          describeSearch($value){
                  return 
          sprintf(__(' is "%1$s"','wp-custom-fields-search'),$value);
              }
          }
          class 
          LikeComparison extends Comparison{
              function 
          addSQLWhere($field,$value){
                  return 
          $this->getLikeString($field,$value);
              }
              function 
          getLikeString($field,$value){
                  return 
          "$field LIKE '%$value%'";
              }
              function 
          describeSearch($value){
                  return 
          sprintf(__(' contains "%1$s"','wp-custom-fields-search'),$value);
              }
          }

          class 
          WordsLikeComparison extends LikeComparison {
              function 
          addSQLWhere($field,$value){
                  
          $words explode(" ",$value);
                  
          $like = array(1);
                  foreach(
          $words as $word){
                      
          $like[] = $this->getLikeString($field,$word);
                  }
                  return 
          "(".join(" AND ",$like).")";
              }
              function 
          describeSearch($value){
                  return 
          sprintf(__(' contains "%1$s"','wp-custom-fields-search'),join('"'.__(" and ",'wp-custom-fields-search').'"',explode(" ",$value)));
              }
          }
          class 
          LessThanComparison extends Comparison{
              function 
          addSQLWhere($field,$value){
                  return 
          "$field < '$value'";
              }
              function 
          describeSearch($value){
                  return 
          sprintf(__(' less than "%1$s"','wp-custom-fields-search'),$value);
              }
          }
          class 
          AtMostComparison extends Comparison{
              function 
          addSQLWhere($field,$value){
                  return 
          "$field <= '$value'";
              }
              function 
          describeSearch($value){
                  return 
          sprintf(__(' at most "%1$s"','wp-custom-fields-search'),$value);
              }
          }
          class 
          AtLeastComparison extends Comparison{
              function 
          addSQLWhere($field,$value){
                  return 
          "$field >= '$value'";
              }
              function 
          describeSearch($value){
                  return 
          sprintf(__(' at least "%1$s"','wp-custom-fields-search'),$value);
              }
          }
          class 
          MoreThanComparison extends Comparison{
              function 
          addSQLWhere($field,$value){
                  return 
          "$field > '$value'";
              }
              function 
          describeSearch($value){
                  return 
          sprintf(__(' more than "%1$s"','wp-custom-fields-search'),$value);
              }
          }
          class 
          RangeComparison extends Comparison{
              function 
          addSQLWhere($field,$value){
                  list(
          $min,$max) = explode("-",$value);
                  
          $where=1;
                  if(
          strlen($min)>0$where.=" AND $field >= $min";
                  if(
          strlen($max)>0$where.=" AND $field <= $max";
                  return 
          $where;
              }
              function 
          describeSearch($value){
                  list(
          $min,$max) = explode("-",$value);
                  if(
          strlen($min)==0) return sprintf(__(' less than "%1$s"','wp-custom-fields-search'),$max);
                  if(
          strlen($max)==0) return sprintf(__(' more than "%1$s"','wp-custom-fields-search'),$min);
                  return 
          sprintf(__(' between "%1$s" and "%2$s"','wp-custom-fields-search'),$min,$max);
              }
          }
          class 
          NotEqualComparison extends Comparison {
              function 
          addSQLWhere($field,$value){
                  return 
          "$field != '$value'";
              }
              function 
          describeSearch($value){
                  return 
          sprintf(__(' is not "%1$s"','wp-custom-fields-search'),$value);
              }
          }

          class 
          BaseJoiner extends ParameterisedObject {
              function 
          BaseJoiner($name=null,$params=array()){
                  
          $this->__construct($name,$params);
              }
              function 
          __construct($name=null,$params=array()){
                  
          parent::__construct($params);
                  
          $this->name=$name;
              }
              function 
          sql_join($join,$name,$index,$value,$comparison){
                  return 
          $join;
              }
              function 
          shouldJoin($value,$comparison){
                  return 
          $this->param('required',false) || $comparison->shouldJoin($value);
              }
              function 
          process_where($where){
                  return 
          $where;
              }
              function 
          needsField(){
                  return 
          true;
              }

              function 
          getField($name,$index){
                  throw new 
          Exception(get_class($this).".getField not implemented");
              }
              function 
          sql_order($order,$name,$index,$value,$comparison){
                  
          $field $this->getField($name,$index);
                  return 
          $comparison->sql_order($order,$field,$value);
              }

              function 
          getHeirarchyOfOptions($name){
                  return array(
                      
          'root'=>$this->getAllOptions($name)
                  );
              }
          }
          class 
          CustomFieldJoiner extends BaseJoiner{
              function 
          CustomFieldJoiner($name,$params){
                  
          $this->__construct($name,$params);
              }
              function 
          __construct($name,$params){
                  
          $this->params $params;
              }
              function 
          param($key,$default=null){
                  if(
          array_key_exists($key,$this->params)) return $this->params[$key];
                  return 
          $default;
              }
              function 
          sql_restrict($name,$index,$value,$comparison){
                  
          $table 'meta'.$index;
                  
          $field "$table.meta_value".($this->param('numeric',false)?'*1':'');
                  
          $comp " AND ".$comparison->addSQLWhere($field,$value);
                  return 
          $comp;
              }
              function 
          sql_join_restrict($name,$index,$value,$comparison){
                  
          $table 'meta'.$index;
                  if(
          $name!='all')
                      return 
          " AND ( $table.meta_key='$name' ) ";
                  return 
          "";
              }
              function 
          getField($name,$index){
                  return 
          "meta$index.meta_value";
              }
              function 
          sql_join($join,$name,$index,$value,$comparison){
                  if(!
          $this->shouldJoin($value,$comparison)) return $join;
                  global 
          $wpdb;
                  
          $table 'meta'.$index;
                  return 
          "$join JOIN $wpdb->postmeta $table ON $table.post_id=$wpdb->posts.id";
              }
              function 
          getAllOptions($fieldName){
                  global 
          $wpdb;
                  
          $where='';
                  if(
          $fieldName!='all')
                      
          $where " WHERE meta_key='$fieldName'";
                  
          $q mysql_query($sql "SELECT DISTINCT meta_value FROM $wpdb->postmeta m JOIN $wpdb->posts p ON m.post_id=p.id AND p.post_status='publish' $where");
                  
          $options = array();
                  while(
          $r mysql_fetch_row($q))
                      
          $options[$r[0]] = $r[0];
                  return 
          $options;
              }
              function 
          getSuggestedFields(){
                  global 
          $wpdb;
                  
          $q mysql_query($sql "SELECT DISTINCT meta_key FROM $wpdb->postmeta WHERE meta_key NOT LIKE '\\_%'");
                  
          $options = array('all'=>'All Fields');
                  while(
          $r mysql_fetch_row($q))
                      
          $options[$r[0]] = $r[0];
                  return 
          $options;
              }
          }
          class 
          CategoryJoiner extends BaseJoiner {
              var 
          $default_taxonomy 'category';
              function 
          getField($name,$index){
                  return 
          "meta$index.term_id";
              }
              function 
          sql_restrict($name,$index,$value,$comparison){
                  if(!(
          $value || $this->params['required'])) return $join;
          //        return " AND ( ".$comparison->addSQLWhere($this->getField($name,$index),$value).")";
                  
          return " AND ( (".$comparison->addSQLWhere($this->getField($name,$index),$value).") OR ( ".$comparison->addSQLWhere("meta$index.name",$value).") )";
              }
              function 
          getTaxonomy(){
                  return 
          $this->param('taxonomy',$this->default_taxonomy);
              }
              function 
          getTaxonomyWhere($table){
                  return 
          "`$table`.taxonomy='".$this->getTaxonomy()."'";
              }
              function 
          sql_join($join,$name,$index,$value,$comparison){
                  if(!
          $this->shouldJoin($value,$comparison)) return $join;
                  global 
          $wpdb;
                  
          $table 'meta'.$index;
                  
          $rel 'rel'.$index;
                  
          $tax 'tax'.$index;
                  return 
          $join." JOIN $wpdb->term_relationships $rel ON $rel.object_id=$wpdb->posts.id JOIN  $wpdb->term_taxonomy $tax ON $tax.term_taxonomy_id=$rel.term_taxonomy_id JOIN $wpdb->terms $table ON $table.term_id=$tax.term_id AND ".$this->getTaxonomyWhere($tax);
              }
              function 
          getAllOptions($fieldName){
                  global 
          $wpdb;
                  
          $sql "SELECT distinct t.term_id,t.name FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id JOIN $wpdb->posts p ON tr.object_id=p.id AND p.post_status='publish' WHERE ".$this->getTaxonomyWhere('tt');
                  
          $q mysql_query($sql);
                  if(
          $e mysql_error()) echo "<h1>SQL: $sql</h1>".mysql_error();
                  
          $options = array();
                  while(
          $r mysql_fetch_row($q))
                      
          $options[$r[0]] = $r[1];
                  return 
          $options;
              }
              function 
          needsField(){
                  return 
          false;
              }
              function 
          getHeirarchyOfOptions($name){
                  global 
          $wpdb;
                  
          $sql "SELECT distinct tt.parent,t.term_id,t.name FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id JOIN $wpdb->posts p ON tr.object_id=p.id AND p.post_status='publish' WHERE ".$this->getTaxonomyWhere('tt');
                  
          $q mysql_query($sql);
                  if(
          $e mysql_error()) echo "<h1>SQL: $sql</h1>".mysql_error();
                  
          $options = array();
                  while(
          $r mysql_fetch_row($q)){
                      if(!
          $r[0]) $r[0]='root';
                      
          $options[$r[0]][$r[1]] = $r[2];
                  }
                  return 
          $options;
              }
          }
          class 
          TagJoiner extends CategoryJoiner {
              function 
          getTaxonomy(){
                  return 
          $this->param('taxonomy','post_tag');
              }
          }

          class 
          PostTypeJoiner extends BaseJoiner {
              function 
          process_where($where){
                  global 
          $wpdb;
                  
          $where preg_replace("/AND \($wpdb->posts.post_type *= *'(post|page)'\)/","",$where);
                  return 
          $where;
              }
              function 
          getField($name,$index){
                  global 
          $wpdb;
                  return 
          "$wpdb->posts.post_type";
              }
              function 
          sql_restrict($name,$index,$value,$comparison){
                  if(!(
          $value || $this->params['required'])) return $join;
                  return 
          " AND ( ".$comparison->addSQLWhere($this->getField($name,$index),$value).")";
              }
              function 
          getAllOptions($fieldName){
                  global 
          $wpdb;
                  
          $q mysql_query($sql "SELECT distinct post_type FROM $wpdb->posts p WHERE post_status='publish' ");
                  
          $options = array();
                  while(
          $r mysql_fetch_row($q))
                      
          $options[$r[0]] = $r[0];
                  return 
          $options;
              }
              function 
          needsField(){
                  return 
          false;
              }
          }

          class 
          PostDataJoiner extends BaseJoiner {
              function 
          getField($name,$index){
                  global 
          $wpdb;
                  return 
          "$wpdb->posts.$name";
              }
              function 
          sql_restrict($name,$index,$value,$comparison){
                  if(
          $name=='all'){
                      global 
          $wpdb;
                      
          $table $wpdb->posts;
                      
          $logic = array();
                      foreach(
          $this->getSuggestedFields() as $name=>$desc){
                          if(
          $name=='all') continue;
                          
          $logic[] =  "( ".$comparison->addSQLWhere("$table.$name",$value).") ";
                      }
                      
          $logic " AND (".join(" OR ",$logic).")";
                      return 
          $logic;
                  } else {
                      
          $field $this->getField($name,$index);
                      return 
          " AND ( ".$comparison->addSQLWhere($field,$value).") ";
                  }
              }
              function 
          sql_join($join,$name,$index,$value){
                  return 
          $join;
              }
              function 
          getAllOptions($fieldName){
                  global 
          $wpdb;
                  
          $q mysql_query($sql "SELECT $fieldName FROM $wpdb->posts");
                  
          $options = array();
                  while(
          $r mysql_fetch_row($q))
                      
          $options[$r[0]] = $r[0];
                  return 
          $options;
              }
              function 
          getSuggestedFields(){
                  return array(
                      
          'all'=>__('All Fields','wp-custom-fields-search'),
                      
          'post_content'=>__('Body Text','wp-custom-fields-search'),
                      
          'post_title'=>__('Title','wp-custom-fields-search'),
                      
          'post_author'=>__('Author','wp-custom-fields-search'),
                      
          'post_date'=>__('Date','wp-custom-fields-search'),
                  );
              }
          }

          class 
          CategorySearch {
          }

          class 
          CustomSearchField extends SearchFieldBase {
              function 
          CustomSearchField($nameOrParams,$input=false,$comparison=false,$joiner=false){
                  
          CustomSearchField::__construct($nameOrParams,$input,$comparison,$joiner);
              }
              function 
          __construct($nameOrParams,$input=false,$comparison=false,$joiner=false){
                  
          parent::__construct();
                  if(!
          is_array($nameOrParams)){
                      
          $params = array('name'=>$nameOrParams);
                  } else {
                      
          $params $nameOrParams;
                  }
                  
          $this->name = @$params['name'];
                  
          $this->params $params;

                  
          $this->joiner $joiner;
                  
          $this->comparison $comparison;
                  
          $this->input $input;

                  if(!
          is_object($this->input)){
                      
          $input $this->param('input','TextField');
                      
          $this->input = new $input($params);
                  }
                  if(!
          is_object($this->comparison)){
                      
          $comparison $this->param('comparison','LikeComparison');
                      
          $this->comparison = new $comparison();
                  }
                  if(!
          is_object($this->joiner)){
                      
          $joiner $this->param('joiner','CustomFieldJoiner');
                      
          $this->joiner = new $joiner($this->param('name'),$this->params);
                  }


              }
              function 
          setIndex($n){
                  
          $this->index=$n;
              }
              function 
          param($key,$default=null){
                  if(
          array_key_exists($key,$this->params)) return $this->params[$key];
                  return 
          $default;
              }

              function 
          stripInitialForm($form){
                  
          $pref='<!--cs-form-->';
                  if(
          preg_match("/^$pref/",$form)) return $form;
                  else return 
          $pref;
              }

              function 
          form_inputs($form){
                  
          $form $this->stripInitialForm($form);
                  return 
          $form.$this->getInput($this->name,$this->joiner);
              }
              function 
          hasValue(){
                  return 
          $this->getValue();
              }

              function 
          sql_restrict($where){
                  
          $value $this->getValue();
                  if(
          $this->hasValue()){
                      
          $value $this->getValue();
                      
          $my_where = array();
                      
          $index 0;
                      foreach(
          $this->input->splitMultiValues($value) as $value){
                          
          $index++;
                          
          $value $GLOBALS['wpdb']->escape($value);
                          
          $local_where=$this->joiner->sql_restrict($this->name,$index*100+$this->index,$value,$this->comparison);
                          if(
          method_exists($this->joiner,'sql_join_restrict') && $this->comparison->shouldJoin($value)){
                              
          $local_where.=$this->joiner->sql_join_restrict($this->name,$index*100+$this->index,$value,$this->comparison);
                          }
                          
          $my_where[] = $local_where;
                      }
                      
          // TODO: Extend this to support or etc. ??
                      
          $where .= " AND ( 1 ".join("",$my_where)." )";
                  }
                  if(
          method_exists($this->joiner,'process_where'))
                      
          $where $this->joiner->process_where($where);
                  return 
          $where;
              }

              function 
          sql_order($order){
                  
          $value $this->getValue();
                  
          $value $GLOBALS['wpdb']->escape($value);
                  
          $order=$this->joiner->sql_order($order,$this->name,$this->index,$value,$this->comparison);
                  return 
          $order;
              }
              function 
          describeSearch($current){
                  if(
          $this->hasValue()){
                      
          $parts = array();
                      foreach(
          $this->input->splitMultiValues($this->getValue()) as $value){
                          
          $value $this->input->valueToDisplay($value,$this->name,$this->joiner);
                          if(
          $value)
                          {
                              
          $parts[] = $this->comparison->describeSearch($value);
                          }
                      }
                      if(
          $parts)
                          
          $current[] = $this->getLabel()." ".join(" AND ",$parts);
                  }
                  return 
          $current;

              }
              function 
          join_meta($join){
                  global 
          $wpdb;
                  
          $index 0;
                  foreach(
          $this->input->splitMultiValues($this->getValue()) as $value){
                      
          $index++;
                      
          $join=$this->joiner->sql_join($join,$this->name,$index*100+$this->index,$value,$this->comparison);
                  }
                  return 
          $join;
              }

              function 
          getQualifiedName(){
                  return 
          $this->name.'-'.$this->index;
              }
              function 
          getOldValue(){ return $this->getValue(); }
              function 
          getValue(){
                  
          $v $this->input->getValue($this->getQualifiedName(),$this->name);
                  return 
          $v;
              }
              function 
          getLabel(){
                  if(!
          $this->params['label']) $this->params['label'] = ucwords($this->name);
                  return 
          $this->params['label'];
              }

              function 
          isHidden(){
                  return 
          $this->input->param('hidden',false);
              }
              function 
          getInput($wrap=true){
                  
          $input $this->input->getInput($this->getQualifiedName(),$this->joiner,$this->name);
                  if(
          $wrap){
                      
          $input "<div class='searchform-param'><label class='searchform-label'>".$this->getLabel()."</label><span class='searchform-input-wrapper'>$input</span></div>";
                  }
                  return 
          $input;
              }
              function 
          getCSSClass(){
                  return 
          method_exists($this->input,'getCSSClass')?$this->input->getCSSClass():get_class($this->input);
              }
          }

          function 
          wp_custom_search_fields_include_bridges(){
              
          $dir opendir($path dirname(__FILE__).'/bridges');
              while(
          $file readdir($dir)){
                  if(
          is_file("$path/$file") && preg_match("/^[^.].*\.php$/",$file)){
                      require_once(
          "$path/$file");
                  }
              }
          }
          wp_custom_search_fields_include_bridges();

          function 
          wp_custom_fields_search_mark_search($query){
              if(
          array_key_exists('search-class',$_REQUEST))
                  
          $query->is_search true;
          }
          add_action('parse_query','wp_custom_fields_search_mark_search');
          function 
          dump_query($query){ echo "<pre>$query</pre>"; return $query;}
          //add_filter('posts_request','dump_query',1000);


          ?>

          Jetzt nur noch das Fallback für die älteren Browser...

          Kommentar


          • #6
            Beispiele dafür gibt es ja in dem von mir gepostetem Artikel.

            Kommentar


            • #7
              Noch so als Hinweis: PHP hat mit Autofokus nichts zu tun. PHP läuft auf dem Server und wird ausgeführt noch bevor irgendwas beim Client ankommt. Fokus geht also nur clientseitig mit HTML oder JS (siehe Link von FeroXY).

              Kommentar

              Lädt...
              X