lundi 5 octobre 2015

Is there a way to optimize function that is used for returning data in an ajax-call?

I've started creating some plugins (not offically deployed yet) (feel free to use it you want to), and now my goal is to include a custom post type and taxonomy and being able to use Advanced Custom Fields if wanted. The purpose of the plugin is to create a list based on custom taxonomy / custom post types and being able to put that anywhere on any page (with a shortcode) and when selecting anything from that list fetch content from the selected custom post type) and put it into another div without page reload.

This is my code (forgive the swedish part, but it's not neccessary I think for the actual question):

<?php
/*
Plugin Name: ListAjax
Plugin URI: http://ift.tt/1VAqyY1
Description: Display a list and display returned content (from ajax-call) into a div
Version: 0.8.0
Author: Wibergs Web
Author URI: http://ift.tt/1MVBmIx
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 municaplity
        $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
}

The result_div() - function is returning data to the 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? It takes about a second to retrieve information. It does not sound like a lot of time, but when selecting from the selectlist, it seems like forever ;-)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire