Saturday, May 2, 2020

Wordpress Ajax

How to use ajax in wordpress.

In this post I will explain how to create simple ajax function in wordpress. The ajax function will send json data as string.


Enqueue the js file

We create the js file with file name script.js.  What important in this script is localize the script. The ajax will not working if we not localize the script. There is 2 parameter we need to caution. First is myAjax and the second is ajaxurl both two parameters will be called in our js script.


 
wp_enqueue_script( 'my-script-js', get_template_directory_uri() . '/assets/script.js', array(), '01', true );
wp_localize_script('my-script-js', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));

Create js function

Here we will create js function that send json data to php. We will convert json to string, using JSON.stringify. Here is the code:
 
/*-- Json Test --*/
$("#test_json").click(function (e) {
 e.preventDefault();
 var json_data = [{
  "id": 1,
  "first_name": "Rancell",
  "last_name": "Byrkmyr"
 }, {
  "id": 2,
  "first_name": "Ray",
  "last_name": "Hinckes"
 }, {
  "id": 3,
  "first_name": "Cathyleen",
  "last_name": "Crufts"
 }];
 console.log(json_data);

 var json_data_str = JSON.stringify(json_data);
 console.log(json_data_str);

 var data = {
  action:'test_ajax',
  data_json: json_data_str,
 }

 $.ajax({
        type: "post",
        url: my_Ajax.ajax_url,
        data: data,
        dataType: "json",
        success:function(response){
           console.log(response);
        },
        error: function(errorThrown){
           console.log(errorThrown);
        } 
    });

})
/*-- Json Test End  --*/
There is some important thing that we need to have a note:
1. The url we use in ajax is set when we localize the script.
2. action key inside data will be used to call function on the php file.

Create function

Now we will define the function in php that will be called by the js.
we add 2 action wp_ajax_test_ajax and wp_ajax_nopriv_my_action and the function name will be test_ajax_fun. The action name must start with wp_ajax_ and wp_ajax_nopriv_ continued with action name that we use on the javascript. wp_ajax_test_ajax is used when logged in and wp_ajax_nopriv_test_ajax when you not logged in.


add_action("wp_ajax_test_ajax", "test_ajax_fun");
add_action("wp_ajax_nopriv_test_ajax", "test_ajax_fun"); 
function test_ajax_fun(){
 $data_json_str = $_POST['data_json'];
 $data_json_str = stripslashes($data_json_str);
 $data_json_obj = json_decode($data_json_str, true);
 $data_return->status = "new data";
 $data_return->our_data = $data_json_obj;
 echo json_encode($data_return);
 wp_die();
}


you can check this ajax by using inspect on chrome and choose Network.
below is the screenshot:

Friday, May 1, 2020

Create Filter using Algolia

Algolia is a hosted search engine. To make it simple we need the example for that. Let say we have a bunch of data, and hard for we to search all of our data. Then Algolia is the solution. Algolia offering full-text, numerical, and faceted search, capable of delivering real-time results from the first keystroke. The next question is, how we Algolia do that?

Tuesday, November 27, 2018

Mobile Menu with Flex

Here is the simple menu using flex.
See the Pen NEzKJK by hari (@zenasen) on CodePen.


The explanation of the code:

To make the full height menu, the secret is flex.
What we need first is the parent to have height 100%;
html, body{
   height:100%;
   padding:0px;
   margin:0px;
}
The main point is parent (ul) should have style :
display:flex;
flex-direction:column;

flex-direction => make the li element become going to down or become a row

For the children(li)< we need to give style :
flex: 1;

flex:1 => this code make the li element have the full height of the parent with the even distribution for each li element

Standard html menu :



The Style :

html, body{
 height:100%;
 padding:0px;
 margin:0px;
}
.menu-container{
 width:350px;
 height:100%;
 background:#eee;
 padding:10px;
 box-sizing:border-box;
}
.menu{
 height:100%;
 list-style:none;
 padding-left:0px;
 margin:0px;
 display:flex;
 flex-direction:column;
 overflow-Y:scroll
}
.menu::-webkit-scrollbar {
 width:4px;
}
.menu::-webkit-scrollbar-track {
 background:rgba(0,0,0,0.3);
}
.menu::-webkit-scrollbar-thumb {
 background-color: #000;
}
.menu>li{
 border:1px solid #000;
 border-bottom:0px;
 box-sizing:border-box;
 position:relative;
 flex: 1;
 transition:all ease 0.5s;
 min-height:70px;
}
.menu>li:last-child{
 border-bottom:1px solid #000;
}
.menu>li>a{
 display:block;
 width:100%;
 height:70px;
 line-height:50px;
 padding:10px;
 box-sizing:border-box;
 position:absolute;
 top:50%;
 transform:translateY(-50%);
 transition:all ease 0.5s;
}
span.caret{
 display:block;
 min-height:50px;
 height:100%;
 width:50px;
 background:yellow;
 position:absolute;
 top:0px;
 right:0px;
 transition:0px;
 transition:all ease 0.5s;
 cursor:pointer;
}
.menu>li.aktif>a{
 height:50px;
 line-height:30px;
 top:0px;
 transform:translateY(0%);
 z-index:3;
}
.menu>li.aktif>span.caret{
 height:50px;
 z-index:4;
}
.submenu{
 position:absolute;
 top:50px;
 max-height:0px;
 overflow:hidden;
 transition:all ease 0.5s;
 background:#00000055;
 width:100%;
 box-sizing:border-box;
}
.menu>li:nth-of-type(2) .submenu.aktif{
 max-height:126px;
}
.menu>li.aktif:nth-of-type(2){
 min-height:176px;
}
.menu>li:nth-of-type(3) .submenu.aktif{
 max-height:90px;
}
.menu>li.aktif:nth-of-type(3){
 min-height:140px;
}

The Javascript :



$( document ).ready(function() {
  $("span.caret").click(function(){
    var parent_li = $(this).parent("li");
    var submenu = $(this).next();
    if(parent_li.hasClass("aktif") === false){
      parent_li.addClass("aktif");
      setTimeout(function(){
        submenu.addClass("aktif");
      }, 500);
    }else{
      submenu.removeClass("aktif");
      setTimeout(function(){
        parent_li.removeClass("aktif");
      }, 500);
    }
  });
});

Sunday, November 11, 2018

Simple Fixed Header on Srolling

With all the website project I've been working, I already seen something in common. One of those thing is a header. So, here is the 2 header with simple fixed header on scrolling.

1. Header Hide

This header is hide when we scroll the page to bottom by 50px from top, but when you scrolling up, it will shown. I like the header, since we can see all the page without disturbed by header menu, But, some time I miss the header. lol :D

Here is the code :

See the Pen Scrolling Header #1 by hari (@zenasen) on CodePen.


2. Header Shrink

This header is shrink or more tight when we scroll the page to bottom by 50px, but when you scrolling up till you reach the top, the header will grow larger. 

Here is the code :
See the Pen Scrolling Header #2 by hari (@zenasen) on CodePen.

Sunday, December 17, 2017

How To Create Widget in Siteorigin Wordpress

Paste this code in Theme > function.php
// this for hook 
function my_awesome_widgets_collection($folders){
    $folders[] = dirname(__FILE__).'/../widgets/';
    return $folders;
}
add_filter('siteorigin_widgets_widget_folders', 'my_awesome_widgets_collection');


// this for add new widget group
function imm_add_widget_tabs($tabs) {
    $tabs[] = array(
        'title' => __('Imm Widgets', 'imm_widget'),
        'filter' => array(
            'groups' => array('imm_widget')
        )
    );

    return $tabs;
}
add_filter('siteorigin_panels_widget_dialog_tabs', 'imm_add_widget_tabs', 20);

hook.php is place where i code on top.

widgets folder is place for all widget

the widget we use as example is imm-carousel

Folder Structure.

 
//***
<?php
/*
Widget Name: Imm Carousel
Description: Carousel
Author: Hari Seanli
Author URI: https://www.islandmediamanagement.com/
Widget URI: https://www.islandmediamanagement.com/,
Video URI: https://www.islandmediamanagement.com/
*/

class Imm_Carousel_Widget extends SiteOrigin_Widget {

 function __construct() {
     //Here you can do any preparation required before calling the parent constructor, such as including additional files or initializing variables.

     //Call the parent constructor with the required arguments.
     parent::__construct(
         // The unique id for your widget.
         'imm-carousel',

         // The name of the widget for display purposes.
         __('Imm Carousel Widget', 'imm-carousel-widget-text-domain'),

         // The $widget_options array, which is passed through to WP_Widget.
         // It has a couple of extras like the optional help URL, which should link to your sites help or support page.
         array(
             'description' => __('A hello world widget.', 'hello-world-widget-text-domain'),
             'help'        => 'http://example.com/hello-world-widget-docs',
             'panels_groups' => array('imm_widget')
         ),

         //The $control_options array, which is passed through to WP_Widget
         array(
         ),

         //The $form_options array, which describes the form fields used to configure SiteOrigin widgets. We'll explain these in more detail later.
         array(
             'text' => array(
                 'type' => 'text',
                 'label' => __('Hello world! goes here.', 'siteorigin-widgets'),
                 'default' => 'Hello world!'
             ),
         ),

         //The $base_folder path string.
         plugin_dir_path(__FILE__)
     );
 }

 function get_template_name($instance) {
     return 'imm-carousel-template';
 }

 function get_template_dir($instance) {
     return 'hw-templates';
 }

}
siteorigin_widget_register('imm_carousel_widget', __FILE__, 'Imm_Carousel_Widget');



?>
<div>
    <?php echo wp_kses_post($instance['text']) ?>
</div>