有没有办法优化用于在AJAX调用中返回数据的函数?

时间:2015-10-06 作者:bestprogrammerintheworld

我已经开始创建一些插件(尚未正式部署)(您可以随意使用),现在我的目标是包括自定义帖子类型和分类,并能够在需要时使用高级自定义字段。该插件的目的是基于自定义分类法/自定义帖子类型创建一个列表,并能够将该列表放在任何页面的任何位置(带有短代码),并且当从该列表中选择任何内容时,从所选自定义帖子类型中提取内容,并将其放入另一个div中,而无需重新加载页面。

这是我的准则(请原谅瑞典语部分,但我认为对于实际问题,这不是必要的):

<?php
/*
Plugin Name: ListAjax
Plugin URI: http://www.wibergsweb.se/plugins/listajax
Description: Display a list and display returned content (from ajax-call) into a div
Version: 0.8.0
Author: Wibergs Web
Author URI: http://www.wibergsweb.se/
License: GPL
Copyright: Wibergs Web
*/
defined( \'ABSPATH\' ) or die( \'No access allowed!\' );

if( !class_exists(\'listajax\') ) {

class listajax
{
    private $errormessage = null;


    /*
    *  Constructor
    *
    *  This function will construct all the neccessary actions, filters and functions for the listajax plugin to work
    *
    *
    *  @param   N/A
    *  @return  N/A
    */  
    public function __construct() {                        
        //These are needed and should only register custom post types when really neccessary
        register_activation_hook( __FILE__, array( $this, \'activate\' ) );                        
        add_action( \'init\', array( $this, \'register_post_types\' ) );

        //Iniate jquery and css
        add_action( \'wp_enqueue_scripts\', array($this, \'js_css\' ) );                             
    }


    /*
     *  error_notice
     * 
     *  This function is used for handling administration notices when user has done something wrong when initiating this object
     *  Shortcode-equal to: No shortcode equavilent
     * 
     *  @param N/A
     *  @return N/A
     *                 
     */                 
    public function error_notice() {
            $message = $this->errormessage;
            echo "<div class=\\"error\\"><strong>ListAjax error:</strong><p>$message</p></div>"; 
    }


    public function activate() {
            $this->register_post_types();
            flush_rewrite_rules(); 
    }


    /*
     *  register_post_types
     * 
     *  This function register post types and taxonomies
     * 
     *  @param N/A
     *  @return N/A
     *                 
     */                    
    public function register_post_types() {
        $municipality_labels = array(
              \'name\' => \'Kommun\',
              \'singular_name\' => \'Kommun\',
              \'add_new\' => \'Lägg till\',
              \'add_new_item\' => \'Lägg till ny kommun\',
              \'edit_item\' => \'Redigera kommun\',
              \'new_item\' => \'Ny kommun\',
              \'all_items\' => \'Alla kommuner\',
              \'view_item\' => \'Visa kommun\',
              \'search_items\' => \'Sök kommuner\',
              \'not_found\' => \'Inga kommuner funna\',
              \'not_found_in_trash\' => \'Inga kommuner funna i sopkorgen\',
              \'parent_item_colon\'  => \'\',
              \'menu_name\' => \'Kommuner\'
            );
            $municipality_args = array(
              \'labels\' => $municipality_labels,
              \'public\' => true,
              \'publicly_queryable\' => true,
              \'show_ui\' => true,
              \'show_in_menu\' => true,
              \'query_var\' => true,
              \'rewrite\' => array( \'slug\' => \'kommun\' ),
              \'capability_type\' => \'post\',
              \'has_archive\' => \'kommuner\',
              \'hierarchical\' => false,
              \'menu_position\' => null,
              \'supports\' => array(\'title\',\'editor\',\'author\',\'comments\'),      
            );
            register_post_type( \'municipality\', $municipality_args );


            //Register custom taxonomy for distict
            $district_cat_labels = array(
              \'name\' => \'Område\',
              \'singular_name\' => \'Område\',
              \'search_items\' => \'Sök område\',
              \'all_items\' => \'Alla områden\',
              \'parent_item\' => \'Område - förälder\',
              \'parent_item_colon\' => \'Föräldra område:\',
              \'edit_item\' => \'Redigera område\',
              \'update_item\' => \'Uppdatera område\',
              \'add_new_item\' => \'Lägg till nytt område\',
              \'new_item_name\' => \'Namn på nytt område\',
              \'menu_name\' => \'Områden\'     
            );
            $district_cat_args = array(
              \'hierarchical\' => true,
              \'labels\' => $district_cat_labels,
              \'show_ui\' => true,
              \'show_admin_column\' => true,
              \'query_var\' => true,
              \'rewrite\' => array(\'slug\' => \'omraden\')
            );
            register_taxonomy( \'district\', array(\'municipality\'), $district_cat_args );                        
    }

    /*
     *  init
     * 
     *  This function initiates the actual shortcodes (at each pageload)
     * 
     *  @param N/A
     *  @return N/A
     *                 
     */        
    public function init() {                           
        //Add shortcode
        add_shortcode( \'lajax-show\', array($this, \'show\') );
        add_shortcode( \'lajax-contactinfo\', array($this, \'show_contactinfoblock\') );

        //Initate ajax-functionality
        add_action( \'wp_ajax_set_contactinfo\', array ( $this, \'set_resultdiv\') );
        add_action( \'wp_ajax_nopriv_set_contactinfo\', array ( $this, \'set_resultdiv\') );
    }



    public function set_resultdiv() {                    
        $post_id = $_POST[\'post_id\'];
        $post_info = get_post($post_id, ARRAY_A); //Array for better performance
        $post_content = $post_info[\'post_content\']; //If there any content in post , then show this first

        $html .= $post_content;                        

        //If using ACF (Advanced Custom Fields plugin) with get_fields()-function
        if( function_exists( \'get_fields\' ) ) {                            
            $fields_cpt = get_fields($post_id);

            if (is_array($fields_cpt)) {

                //Loop through fields of current post
                foreach($fields_cpt as $field_key => $field_value) {
                        //If field value starts with http, then take for granted it should be linked
                        if (substr($field_value, 0,4) === \'http\') {
                                $new_fieldvalue = \'<a target="_blank" href="\' . $field_value . \'">\' . $field_value . \'</a>\'; 
                        }
                        else {
                                $new_fieldvalue = $field_value; //"Normal" value
                        }

                        //Get the label that user has typed in administration
                        $field = get_field_object($field_key, $post_id, array(\'load_value\' => false));                                                        
                        $label = $field[\'label\'];

                        //Do the actual output of each label and value 
                        //that is defined in ACF for the custom post type
                        $html .= \'<span class="lajax-wrapper">\';
                        $html .= \'<span class="lajax-title">\' . $label. \'</span>\';
                        $html .= \'<span class="lajax-value">\' . $new_fieldvalue . \'</span>\';
                        $html .= \'</span>\';
                }
            }              

        }

        echo $html;                        
        wp_die();
        return;
    }                

    public function js_css() {                       
       wp_enqueue_script(
               \'listajaxjs\',
               plugins_url( \'/js/wibergsweb.js\' , __FILE__)
       );                          
   }            

    public function show_contactinfoblock() {
        $html = \'<div class="lajax-container">\';
        $html .= \'<div id="contactinfo"></div>\';
        $html .= \'</div>\';
        return $html;
    }

    /*
     *  show
     * 
     *  This functions shows a list  based on a taxonomy (that is identified by slug)
     * 
     *  @param N/A
     *  @return string      date
     *                 
     */      
    public function show( $attrs ) {
        $defaults = array(
                \'slug\' => null, //Must be set by user!
                \'result_div\' => \'#contactinfo\'
        );                        

        //Extract values from shortcode and if not set use defaults above
        $args = wp_parse_args( $attrs, $defaults );
        extract( $args ); //slug = $args{\'slug\'] etc

        //Validation
        if ($args[\'slug\'] === null) {
                $this->errormessage = \'Slug of district must be set - show()\';
                add_action( \'admin_notices\', array( $this,\'error_notice\' ) ); 
                return;
        }

        //Get posts of selected district
        $posts_array = get_posts(
            array(
                \'posts_per_page\' => -1,
                \'post_type\' => \'municipality\',
                \'tax_query\' => array(
                    array(
                        \'taxonomy\' => \'district\',
                        \'field\' => \'slug\',
                        \'terms\' =>  $args[\'slug\']
                    )
                )
            )
        );

        //Create the actual selectlist based on selected district
        $result_div = $args[\'result_div\'];

        $html = \'<form name="ajaxlistform" class="ajaxlistform">\';
        $html .= \'<select class="ajaxlist" data-resultdiv="\' . $result_div . \'">\';
        foreach($posts_array as $pa) {
            $id = $pa->ID;
            $title = $pa->post_title;
            $html .= \'<option value="\' . $id . \'">\' . $title . \'</option>\';                            
        }
        $html .= \'</select></form>\';

        return $html;             
    }

}        
$listajax = new listajax();
$listajax->init(); //Execute AFTER user defined settings are set
}
Theresult_div() - 函数正在将数据返回到javascript:

jQuery(function ($) {
    //Ajax-retrieve value from selected custom post type (that is shown in list)          
    $(\'.ajaxlistform\').on(\'change\', \'.ajaxlist\', function(e) {   
       var t = $(this);
       var post_id = $(this).val();  //Value from selectlist

        var listajaxvalues = $.ajax({            
            type: \'POST\',
            data:{
                action: \'set_contactinfo\',    
                post_id: post_id
            },
            url: \'/wp-admin/admin-ajax.php\',
            dataType: \'html\'
        });

        //Put data into resultdata div that is set inte data-resultdiv attribute
        listajaxvalues.done(function(data) {
                var result_data = t.data(\'resultdiv\');
                $(result_data).html(data);
                return;
        });                        

        listajaxvalues.fail(function(ts) {           
            alert(ts.responseText);
       });


    });

});
Is there a way to optimize (in terms of speed) the result_div() - function? 检索信息大约需要一秒钟。听起来时间不多,但从selectlist中选择时,似乎是永远的;-)

1 个回复
最合适的回答,由SO网友:Max 整理而成

因为您没有使用$field_value 之后if-else, 你可以开始重写if

if (substr($field_value, 0,4) === \'http\') {
   $field_value = \'<a target="_blank" href="\' . $field_value . \'">\' . $field_value . \'</a>\'; 
} 
/* else {
   no else statement here!
} */
以后再这样使用:

$html .= \'<span class="lajax-value">\' . $field_value . \'</span>\';
更重要的是,您可能希望尝试在循环定义中使用引用

foreach($fields_cpt as $field_key => &$field_value)
如果您想更进一步,可以将url检查移动到客户端,以便在呈现内容后运行。

相关推荐

WordPress AJAX错误400向远程站点发送数据的错误请求

我正在使用发件人。net获取电子邮件订阅列表。这个网站给了我一些信息,可以将用户的电子邮件添加到订阅列表中。我想使用WordPress ajax来实现这一点。但它返回错误400错误请求。我的代码是:文件ajax新闻脚本。js公司: jQuery(document).ready(function($){ // Perform AJAX send news on form submit $(\'form#fnews\').on(\'submit\', funct