Excellent Programming Tricks

Frequently Used WordPress Functions | Theme Development

    Ref: https://developer.wordpress.org/
    1. Object operator ->
    2. Array operator =>
    3. Theme Name (from style.css)
      1. wp_get_theme();
    4. Directory/Url
      1. Current File - __FILE__
        1. C:\xampp\htdocs\wpyt\wp-content\themes\myTheme\functions.php
      2. Root Directory - dirname( __FILE__ ) );
        1. C:\xampp\htdocs\wpyt\wp-content\themes\myTheme
      3. Root Theme Directory - dirname(dirname( __FILE__ )) );
        1. C:\xampp\htdocs\wpyt\wp-content\themes\myTheme
        2. Suppose you want to access plugin files
      4. Root URI - get_template_directory_uri() );
        1. http://localhost/wpyt/wp-content/themes/myTheme
      5. Access style.css - get_stylesheet_uri();
        1. http://localhost/wpyt/wp-content/themes/myTheme/style.css
        2. wp_enqueue_style( 'guddi', get_stylesheet_uri(), array( 'bootstrap', 'font-awesome' ), 1.01, 'screen' );
      6. admin_url('admin-ajax.php');
    5. Convert data types
      1. add_query_arg( $fonts, "https://fonts.googleapis.com/css" );
        1. Add key and value with url and produce string.
        2. https://fonts.googleapis.com/css?family=Lato:400,400i&subset=latin
    6. Customize Register
      1. function galib_customizer_register($wp_customize){
            $wp_customize->add_section('galib_header_area', array(
                'title'         => __('Header Area', 'iftekhargalib'),
                'description'   => 'Upload Logo'
            ));
            $wp_customize->add_setting('galib_logo', array(
                'default'       => get_bloginfo('template_directory').'/assets/img/logo.png',
            ));
            $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'galib_logo', array(
                    'label'         => 'Logo Upload',
                    'description'   => 'Brif desc',
                    'setting'       => 'galib_logo',
                    'section'       => 'galib_header_area'
                )
            ));
        }
      2. <img src="<?php echo get_theme_mod('galib_logo'); ?>" alt="">
    7. Fonts
      1. function galib_add_google_fonts(){
            wp_enqueue_style( 'galib_google_fonts', 'https://fonts.googleapis.com/css2?family=Josefin+Sans:ital,wght@0,100..700;1,100..700&family=Oswald:wght@200..700&display=swap', false);
        }
        add_action('wp_enqueue_scripts','galib_add_google_fonts');

    8. Register Nav Menu
      1. register_nav_menu('main_menu',__('Main Menu','iftekhargalib'));
      2. <?php wp_nav_menu( array('theme_location' => 'main_menu', 'menu_id' => 'nav') ); ?>
    9. Control class
      1. function galib_customizar_register($wp_customize){ 

          $wp_customize->add_section('galib_menu_option', array(
            'title' => __('Menu Position Option', 'iftekhargalib'),
            'description' => 'ABCD'
          ));

          $wp_customize->add_setting('galib_menu_position', array(
            'default' => 'right_menu',
          ));

          $wp_customize-> add_control('galib_menu_position', array(
            'label' => 'Menu Position',
            'description' => 'Select your menu position',
            'setting' => 'ali_menu_position',
            'section' => 'ali_menu_option',
            'type' => 'radio',
            'choices' => array(
              'left_menu' => 'Left Menu',
              'right_menu' => 'Right Menu',
              'center_menu' => 'Center Menu',
            ),
          ));

        }

        add_action('customize_register', 'ali_customizar_register');
      2.  <div id="header_area" class="<?php echo get_theme_mod('ali_menu_position'); ?>">
      3.  
    10. Theme Customize CSS
    11. BxSlider
    12. <?php the_content(); ?> shows sticky post fast. 
    13. Shortcode 
      1. Audio Shortcode
        1. [audio src=""][/audio]
      2. Video Shortcode
        1. [video src=""][/video]
    14. Excerpt Expand
      1. function galib_excerpt_more($more){
          return '<a class="redmore" href="'.get_permalink( $post->ID) . '">' . 'Read More' . '</a>';
        }
        add_filter('excerpt_more', 'galib_excerpt_more');
    15. Excerpt Length
      1. function galib_excerpt_lenght($length){
          return 40;
        }
        add_filter('excerpt_length', 'galib_excerpt_lenght', 999);
    16. Page Nav
      1. function galib_pagenav(){
          global $wp_query;
          $pages ='';
          $max = $wp_query->max_num_pages;
          if(!$current = get_query_var('paged')) $current = 1;
          $args1['base'] = str_replace(991, '%#%', get_pagenum_link(991));
          $args1['total'] = $max;
          $args1['current'] = $current;
          $total = 1;
          $args1['prev_text'] = 'Prev';
          $args1['next_text'] = 'Next';
          if ($max > 1) echo '</pre>
            <div class="wp_pagenav">';
              if ($total == 1 && $max > 1) $pages = '<p class="pages"> Page ' .$current . '<span>of</span>' . $max . '</p>';
              echo $pages."ss" . paginate_links($args1);
              if ($max > 1 ) echo '</div><pre>';
        }
    17. var_export();
    18. The mime type
    19. Enqueue
      1. Front End
        1. function guddi_scripts(){
           wp_enqueue_style( 'custom', get_template_directory_uri() . '/css/custom.css', array(), '1.0.0', 'all' ); 
           wp_deregister_script( 'jquery' );
           wp_register_script( 'jquery' , get_template_directory_uri() . '/js/jquery.js', false, '1.11.3', true );
           wp_enqueue_script( 'jquery' ); 
           wp_enqueue_script( 'guddi', get_template_directory_uri() . '/js/custom_guddi_js.js', array('jquery'), '1.0.0', true );
          }
          add_action( 'wp_enqueue_scripts', 'guddi_scripts' );
      2. Back End
        1. Good practice first register and hook wise enqueue
        2. function admin_scripts( $hook ){
        3. wp_register_style( 'admin', get_template_directory_uri() . '/css/admin.css', array(), '1.0.0', 'all' ); --css
          wp_register_script( 'admin-js', get_template_directory_uri() . '/js/admin.js', array('jquery'), '1.0.0', true ); --js  $pages_array = array(   'toplevel_page_guddi_css', 'my_custom_page'  );  //PHP 7  if( in_array( $hook, $pages_array ) ){   wp_enqueue_style( 'admin' );  }  if( 'toplevel_page_guddi' == $hook ){   wp_enqueue_media(); //Automatically handle media related functions   wp_enqueue_script( 'admin-js' );  } } add_action( 'admin_enqueue_scripts', 'admin_scripts' );
    20. Print
      1. _e('text'); --_e( $text, $domain = 'default' )
      2. __('text'); -- __( $text, $domain = 'default' )
    21. POST
      1. <main id="main" class="site-main" role="main">
           <div class="container">
            <?php
                    if( have_posts() ):
                         while( have_posts() ): the_post();
                                get_template_part( 'template-parts/content', get_post_format());
                          endwhile;
                    endif;
            ?>
          </div><!-- .container -->
         </main>
      2. Post container also have header, body and footer.
      3. Suppose index.php contains blog post but Setting->Reading front-> blog. Means just create a page title blog then appears blog page with in index.php. 
      4. content/content-image.php
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
         <header class="post-header text-center">
                 <?php the_title( '<h1 class="post-title"><a href="'. esc_url( get_permalink() ) .'" rel="bookmark">', '</a></h1>'); ?>
                  <div class="post-meta">
                            <?php echo post_meta(); ?>
                   </div>
           </header>
          <div class="post-content">
                      <?php if( has_post_thumbnail() ):
                                echo $featured_image = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );
                        ?>
                       <a href="<?php the_permalink(); ?>">
                              <div style="background-image: url(<?php echo $featured_image; ?>);"></div>
                         </a>
                     <?php endif; ?>
                  <?php the_excerpt(); ?>
                  <a href="<?php the_permalink(); ?>" class="btn btn-sunset"><?php _e( 'Read More' ); ?></a>
           </div><!-- post-content -->
         <footer class="post-footer">
          <?php echo post_footer(); ?>
         </footer>
        </article>
      5. function post_meta(){
         $posted_on = human_time_diff( get_the_time('U') , current_time('timestamp') );

         $categories = get_the_category();
         $separator = ', ';
         $output = '';
         $i = 1;

         if( !empty($categories) ):
          foreach( $categories as $category ):
           if( $i > 1 ): $output .= $separator; endif;
           $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( 'View all posts in%s', $category->name ) .'">' . esc_html( $category->name ) .'</a>';
           $i++;
          endforeach;
         endif;

         return '<span class="posted-on">Posted <a href="'. esc_url( get_permalink() ) .'">' . $posted_on . '</a> ago</span> / <span class="posted-in">' . $output . '</span>';
        }
      6. function post_footer(){

         $comments_num = get_comments_number();
         if( comments_open() ){
          if( $comments_num == 0 ){
           $comments = __('No Comments');
          } elseif ( $comments_num > 1 ){
           $comments= $comments_num . __(' Comments');
          } else {
           $comments = __('1 Comment');
          }
          $comments = '<a class="comments-link" href="' . get_comments_link() . '">'. $comments .' <span class="sunset-icon sunset-comment"></span></a>';
         } else {
          $comments = __('Comments are closed');
         }

         return '<div class="post-footer-container"><div class="row"><div class="col-xs-12 col-sm-6">'. get_the_tag_list('<div class="tags-list"><span class="sunset-icon sunset-tag"></span>', ' ', '</div>') .'</div><div class="col-xs-12 col-sm-6 text-right">'. $comments .'</div></div></div>';
        }
    22. Custom class inside Post Query
      1. if( have_posts() ):
              while( have_posts() ): the_post();
                    $customClass = 'myClass';
                    set_query_var( 'custom-class-id-abc', $customClass );
                    get_template_part( 'template-parts/content', get_post_format() );
              endwhile;
          endif;
      2. contact.php
        1. $class = get_query_var('custom-class-id-abc');
        2. <article id="post-<?php the_ID(); ?>" <?php post_class( array( 'my-post-content-class' , $class) ); ?>>
    23. Get all post without using WP_Query()
      1. $tables = get_posts( array( 'post_type' => 'table', 'numberposts' => -1 ) );
    24. Delete Post
      1. foreach( $tables as $table ) {
         wp_delete_post( $table->ID, true );
        }
    25. Image
      1. Header Image Location
        1. get_header_image(); [http://localhost/wpyt/wp-content/themes/graphene/images/headers/myImage.jpg]
    26. Global Variable 
      1. Declare global variable for accessing the core functionality of your requirement.
      2. global $wpdb [Access database via SQL].
      3. global $wp_styles; [Initialize style sheet].
      4. global $post; [Current post status for the loop].
    27. Ajax
      1. admin-ajax.php file is required. So, use data-url="<?php echo admin_url('admin-ajax.php'); ?>" for url.
      2. myajax.php (theme->myajax.php) | functions.php require link
        1. add_action( 'wp_ajax_nopriv_guddi_function_load_more', 'guddi_callback_load_more'); --nopriv means can call if user not login.
        2. add_action( 'wp_ajax__guddi_function_load_more', 'guddi_callback_load_more'); --Called only for loged user.
        3. function guddi_callback_load_more(){
                  echo 'test;
          }
        4.  
      3. Custom.js
        1.  $(function(){  
             $(document).ready(function() {   
               $(document).on('click', '.guddi-load-more', function(){  
                   var page = $(this).data('page');  
                   var ajaxurl = $(this).data('url')  
                   $.ajax({  
                       url: ajaxurl,  
                       type:'post',  
                       data: {  
                           page: page,  
                           action: 'guddi_function_load_more'  
                       },  
                       error: function( response){  
                           console.log(response);  
                        },  
                       success: function(){  
                           $('.guddi-posts-container').append( response );  
                        }  
                   });  
                });  
              });  
            });  
          
    28. Insert Post
      1. wp_insert_post();
    29. Comments
      1. Comment ID = comment_ID();
      2. comment_text( $comment_ID );
      3. wp_get_current_commenter();
    30. Template
      1. Capture template
        1.  get_template_part( 'template-parts/content', get_post_format());
        2. locate_template( $template_names, $load, $require_once );
    31. Admin Menu
      1. Actually built in functions parameter play a major role so naming convention is very important.
      2. function guddi_add_menu_admin_page(){
                   //generation of our admin page
        1. add_menu_page( 'My Theme Title', 'Settings', 'manage_options', 'page_guddi', 'add_menu_function_dashboard', get_template_directory_uri() . '/img/sunset-icon.png or dashicons-hammer', 110 );
        2. add_submenu_page( 'page_guddi', 'Theme Options', 'General', 'manage_options', 'page_guddi', 'add_menu_function_dashboard' );
        3. add_submenu_page( 'iftekhar_guddi', 'CSS Options', 'Custom CSS', 'manage_options', 'page_guddi_css', 'add_submenu_function_css');
      3.  }
      4. add_action( 'admin_menu', 'guddi_add_menu_admin_page');
      5. add_menu_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function =' ', string $icon_url = ' ', int position = ' ' );
      6. add_submenu_page( string $parent_slug, string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '' );
        1. When main menu appear in submenu: use main menu slug '$menu_slug' with submenu slug. Other submenu slug has their identical slug. Parent slug would be same. Also, function should be same name but different name needs two function. Actually we want same page with main menu and sub main.
        2.  add_menu_page( 'My Page Title', 'Settings', 'manage_options', 'excellent_tricks', 'my_function', 'icon', 110 );
           //Sub Pages
           add_submenu_page( 'excellent_tricks', 'My page title', 'General', 'manage_options', 'excellent_tricks', 'my_function' );
      7. function add_menu_function_dashboard(){
         require_once( get_template_directory() . '/inc/templates/guddi-admin.php' );
        }
      8. function add_submenu_function_css(){
        echo '<h1> Custom Css<h1>';
        }
    32. Sub Menu Tuning 
      1. function submenu_tuning(){
        1. register_setting( 'tuning-register-setting-field-group-1', 'first_variable' );
        2. register_setting( 'tuning-register-setting-field-group-1', 'second_variable', 'register_function_sanitize' );
        3. add_settings_section( 'tuning-id-section-options', 'Sidebar Option', 'add_section_function_1', 'page_guddi');
        1. add_settings_field( 'tuning-field-id-name', 'Full Name', 'add_field_function_name', 'page_guddi', 'tuning-id-section-options');
      2. }
      3. add_action( 'admin_init', 'submenu_tuning' );
      4. function add_section_function_1(){
         echo 'Customize Your Sidebar Information!';
        }
      5. function add_field_function_name(){
                   $firstName = esc_attr( get_option( 'first_variable) );
                    $lastName = esc_attr( get_option( 'second_variable' ) );
                    echo '<input type="text" name="_variable" value="'.$firstName.'" placeholder="First Name" /> <input type="text" name="second_variable" value="'.$lastName.'" placeholder="Last Name" />';
        }
      6. function register_function_sanitize($input){ $output = sanitize_text_field($input); $output = str_replace('-', '', $output); return $output; }
      7. register_setting( $option_group, $option_name, $args = array );
      8. add_settings_section( $id, $title, $callback, $page ); -- $page is actually parent page.
      9. add_settings_field( $id, $title, $callback, $page, $section = 'default', $args = array ); //main call back function
      10. Template Page
        1. settings_errors();
        2. settings_fields( $option_group );
        3. do_settings_sections( $page );
        4. submit_button( $text = null, $type = 'primary', $name = 'submit', $wrap = true, $other_attributes = null );
          1. <h1>Theme Options</h1>
            <?php settings_errors(); ?>
            <form method="post" action="options.php">
             <?php settings_fields('tuning-register-setting-field-group-1' ); ?>
             <?php do_settings_sections( ''page_guddi' ); ?>
             <?php submit_button(); ?>
            </form>
    33. Add Action
      1. add_action( 'admin_menu', 'function_name' );
      2. add_action( 'admin_init', 'submenu_tuning' );
      3. add_action( 'init', 'post_type' );
      4. add_action('after_setup_theme', 'post_type' );
      5. add_action( 'save_post', 'add_meta_box_function_contact_email' );
    34. Custom Post Type (like Post, Page)
      1. Reference: https://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column, https://developer.wordpress.org/reference/functions/register_post_type/https://developer.wordpress.org/reference/functions/register_post_type/  
      2. Basic Custom Post Type | Mainly Use For Grab Variable Value | any_where.php
        1. function custom_post_type() {
              $args = array(
                'public' => true,
                'label'  => 'Message'
              );
              register_post_type( 'message', $args );
          }
          add_action( 'after_setup_theme/init', 'custom_post_type');
    35.  Custom Post Type | Customize totally and add/modify attributes || custom-post-type.php
      1. $contact = get_option( 'activate_confirm' );
         if( @$contact == 1 ){
                   add_action( 'init', 'mycustom_post_type' );
                   add_filter( 'manage_custom-post-contact_posts_columns', 'add_filter_function_contect_columns' ); //Pass variable through the functions
                   add_action( 'manage_custom-post-contact_posts_custom_column', 'add_action_function_contect_column', 10, 2 ); //priority 10. Two function arguments.
                   add_action( 'add_meta_boxes', 'add_meta_box_contact_email' );
                   add_action( 'save_post', 'nonce_action_save_contact_email' );
         }
      2. function mycustom_post_type() {
         $labels = array(
               'name'     => 'Messages',
               'singular_name'  => 'Message',
               'menu_name'   => 'Messages',
               'name_admin_bar' => 'Message'
          );
          $args = array(
               'labels'   => $labels,
               'show_ui'   => true,
               'show_in_menu'  => true,
               'capability_type' => 'post',
               'hierarchical'  => false,
               'menu_position'  => 26,
               'menu_icon'   => 'dashicons-email-alt',
               'supports'   => array( 'title', 'editor', 'author' )
            );

         register_post_type( 'custom-post-contact', $args );
        }
      3. function add_filter_function_contect_columns( $columns ){
                  //unset( $columns['author'] );
                  $newColumns = array();
                  $newColumns['title'] = 'Full Name';
                  $newColumns['message'] = 'Message'; // the_content values
                  $newColumns['email'] = 'Email';
                  $newColumns['date'] = 'Date';
                  return $newColumns;
        }
      4. function add_action_function_contect_column( $column, $post_id ){
               switch( $column ){
                        case 'message' :
                             echo get_the_excerpt();
                             break;
                        case 'email' :
                             $email = get_post_meta( $post_id, '_contact_email_value_key', true );
                             echo '<a href="mailto:'.$email.'">'.$email.'</a>';
                            break;
                }
        }
    36. Embedded media in  POST content.
    37. Meta Box | Custom field in POST/PAGE
      1. function add_meta_box_contact_email() {
         add_meta_box( 'contact_email', 'User Email', 'add_meta_box_function_contact_email', 'custom-post-contact', 'side' );
        }
      2. function add_meta_box_function_contact_email( $post ) {
         wp_nonce_field( 'nonce_action_save_contact_email', 'nonce_name_save_contact_email' );

         $value = get_post_meta( $post->ID, '_contact_email_value_key', true ); //When retrieve data use _ before string name.
         echo '<label for="contact_email_field">User Email Address: </lable>';
         echo '<input type="email" id="contact_email_field" name="contact_email_field" value="' . esc_attr( $value ) . '" size="25" />';
        }
      3. function nonce_action_save_contact_email( $post_id ) {
         if( ! wp_verify_nonce( $_POST['nonce_name_save_contact_email'], 'nonce_action_save_contact_email') ) {
          return;
         }
         if( ! isset( $_POST['nonce_name_save_contact_email'] ) ){
          return;
         }
        if( ! current_user_can( 'edit_post', $post_id ) ) {
          return;
         }
         if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){ //stop auto save.
          return;
         }
         if( ! isset( $_POST['contact_email_field'] ) ) {
          return;
         }
         $data = sanitize_text_field( $_POST['contact_email_field'] );

         update_post_meta( $post_id, '_contact_email_value_key', $data );

        }
      4. add_meta_box( $id, $title, $callback, $screen = null, $context = 'advanced', $priority = 'default', $callback_args = null ); //$context = normal (default), side ... / $priority = high, ...
      5. get_post_meta( $post_id, $key = '', $single = false ); //When retrieve data use _ before string name. //true when single value
      6. update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' );
    38. Option based value through option name
      1. get_option()
      2. $firstName = esc_attr( get_option( 'first_name' ) );
    39. Escaping for HTML attributes
      1. esc_attr
    40. Nonce validation
      1.  wp_nonce_field( $action = -1, $name = '_wpnonce', $referer = true, $echo = true );
      2. wp_verify_nonce( $nonce, $action = -1 )
      3. Action can use multiple time
    41. Sanitize text
      1. sanitize_text_field( $str )
    42. Remove HTML tage
      1. $message = wp_strip_all_tags($_POST["message"]);
    43. Hooks
      1. apply_filters( string $tag, mixed $value )
        1. Call the functions added to a filter hook.
      2. add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
        1. Hook a function or method to a specific filter action.
        2. add_filter( 'settings', 'scripts_version' ); //scripts_version is callback function.
      3. do_action( string $tag, $arg = '' )
        1. Execute functions hooked on a specific action hook.
        2. do_action( 'my_loop' );
    44. WordPress conditional functions
      1. is_active_sidebar( $index );
        1. Return true when find widget.
      2. is_rtl();
        1. True/false, no arguments.
        2. Check current local is rtl or not.
      3. is_ssl()
        1. Check url contains SSL(Secure Sockets Layer).
    45. Shortcode
      1. Use small single letter for shortcode.
      2. User define shortcode name with user define attributes so get attributes by using shortcode_atts().
      3. add_shortcode( $tag, $func );
      4. function $func( $atts, $content = null){}
      5. shortcode_atts( $pairs, $atts, $shortcode = '' )
        1. $pairs - (array) (required) List of user define attributes and defaults.
        2. $atts - (array) (required) User defined attributes in shortcode tag
        3. $shortcode - (string) (optional) Shortcode name to be used by the shortcode_atts_{$shortcode} filter. Actual shortcode name.

    No comments:

    Post a Comment


    Authentic аnd Excellent

    Website

    HTML Template

    Wordpress Theme

    Database applications

    OR

    Application services?

    Excellent Programming Tricks (EPT) || Iftekhar-IT || We develops the Web applications and the WordPress templates. || Excellent Programming Tricks (EPT)

    © 2020 Blogger Theme by Iftekhar IT || Excellent Programming Tricks

    Execllent Programming Tricks. Powered by Blogger.