JustToThePoint English Website Version
JustToThePoint en español
JustToThePoint in Thai

Create a custom WordPress Theme II. Javascript. WordPress Advanced Administration.

WordPress

WordPress is a free, open-source, and very popular website creation platform. It is also a content management system written in PHP.

It is a simple, flexible, user-friendly platform, with key features that include media management, SEO, a huge collection of plugins and themes, and endless options for customization.

Essentials WordPress Plugins that I can’t live without

WordPress plugins are small software apps that integrate and run on top of the WordPress software and allow you to add new features and functionality to your WordPress website.

Security

Security is a multi-layered approach.

  1. You should configure and use two-factor authentication in your webhosting client area and the webhosting control panel. Then, save the QR code in your favorite Password Manager (e.g., KeePassXC -Advanced, Attachment-), and export your Google Authenticator tokens from one smartphone to another smartphone or iPad.
  2. You need a web hosting provider that offers free daily backups for your website files and database.
  3. Generate and download a full website backup with FileZilla (public_html or Home directory /) or using your webhosting control panel. Typically, cPanel, Files, Backups (Download a Full Account Backup) or plesk, File Manager, select all your files and directories, click Add To Archive and then download the file to your PC.
  4. Use a backup plugin like UpdraftPlus - Backup/Restore or All-in-One WP Migration.
  5. Backup your database using PHPMyAdmin: cPanel/plesk, Databases, Export Dump or cPanel, phpMyAdmin, Export, select the “Quick” export method and the “SQL” format, then click Go.
  6. Don’t install many plugins on your WordPress website and disable useless features of your themes and plugins.
  7. Keep your WordPress up-to-date (WordPress, plugins, and themes), but please remember, it is always important to back up your website before upgrading WordPress.

WordPress is built on PHP. You need to keep your themes and plugins up to date. However, keeping your PHP version up-to-date is equally important and it will ensure that your website runs faster and will stay more secure. Log in to your hosting dashboard, PHP settings, and select the version of PHP. You may need to enable Imagick (ImageMagick), too: Edit PHP configuration/Site Tools, Dev, PHP Manager (Cambiar configuraciones PHP), PHP Extensions, imagick.

Child Themes

A child theme inherits the “look and file” of its parent theme and all of its functions, but it allows you to change aspects of your site’s appearance yet still preserve your theme’s look and functionality.

How To Create a Child Theme:

/*
 Theme Name:   JustToThePoint
 Theme URI:    http://justtothepoint.com/twenty-fifteen-child/
 Description:  Twenty Sixteen Child Theme. To use this Child Theme, you must have [twentysixteen](https://wordpress.org/themes/twentysixteen/) parent theme installed.
 Author:       Maximo Nunez (Anawim), Juan
 Author URI:   http://justtothepoint.com
 Template:     twentysixteen
 Version:      1.0.1
 License:      Copyrighted wordpress theme
 License URI:
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  twenty-sisteen-child
*/

/* My Fonts */
@font-face {
	font-family: 'PacificoJTTP';
	src: url('../../../fonts/Pacifico.ttf') format('truetype');
}

@font-face {
	font-family: 'gilligan';
	src: url('../../../fonts/gilligan.eot');
	src: local('☺'), url('../../../fonts/gilligan.woff') format('woff'), url('../../../fonts/gilligan.ttf') format('truetype'), url('../../../fonts/gilligan.svg') format('svg');
	font-weight: normal;
	font-style: normal;
}...
WordPress

WordPress

    <?php
    add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
    function theme_enqueue_styles() {
        wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
        wp_enqueue_style( 'child-style',
            get_stylesheet_directory_uri() . '/style.css',
            array('parent-style')
        );
        /* Add FontAwesome to our WordPress (**). */
        wp_enqueue_style( 'JustToThePoint-font-FontAwesome', get_stylesheet_directory_uri() . '/FontAwesome/css/all.css' );
    }

We need to enqueue or add the parent and child themes stylesheets. get_template_directory_ury() returns the template directory URI for your current theme, get_stylesheet_directory_uri() returns the child’s theme directory URI, and wp_enqueue_style() enqueues a CSS stylesheet.

FontAwesome

FontAwesome is a very popular icon toolkit that offers a wide variety of icons. First, you need to download and copy the fonts (the /webfonts folder and the /css/all.css file) and put them into a folder in your site, typically your project’s assets directory: /httpdocs/wp-content/themes/justtothepoint. I have created a directory FontAwesome under my theme’s directory.

Then, we need to include font Awesome in our WordPress, more specifically you need to edit functions.php (Go to the previous section **). Let’s see some examples:

  <i class="fa-solid fa-code"></i>
  <i class="fa-brands fa-facebook"></i>
  <i class="fa-brands fa-twitter"></i>

Enqueue Your Assets in WordPress, Enable theme support for featured images

Instead of adding your scripts and styles to the header, you should enqueue them in WordPress (functions.php). By doing so, you register them (you inform the CMS (WordPress) about them), and then you enqueue them so they will eventually appear on the front end.

/* Let's allow shortcodes in our sidebar widgets */
add_filter( 'widget_text', 'do_shortcode' );

/* Disable wptexturize in WordPress. wptexturize transforms quotes into so-called smart or curly quotes, and "__" is converted to an "en or mid-sized dash". */
add_filter( 'run_wptexturize', '__return_false' );

function add_java_scripts() {
  wp_enqueue_script( 'myJavaScript', get_stylesheet_directory_uri() . '/js/miJs.js' );
}
add_action( 'wp_enqueue_scripts', 'add_java_scripts' ); 
/* To enqueue scripts and styles, you’ll need to use the wp_enqueue_scripts hook. We are adding the Javascript source file url_my_theme/js/miJs.js that we will use in the next section. */

/* Enable theme support for featured images */
add_theme_support('post-thumbnails');

Adding JavaScript in WordPress

“JavaScript is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for Web pages,” Msdn web docs, Guides, JavaScript.

To add custom JavaScript to your site, you need to either use a plugin (Insert Headers and Footers by WPBeginner) or enqueue it in WordPress (functions.php) as explained previously. Let’s see an example:

Do you want to know the estimated peak blood alcohol concentration (EBAC)? For instance EBAC(2, 0, 80, 2) means 2 standard drinks, a man, 80 Kg, 2 hours.

SD is the number of standard drinks. “The standard drinks measure is “a simple way for you to work out how much alcohol you are drinking. It measures the amount of pure alcohol in a drink. One standard drink equals 10 grams of pure alcohol”, HPA’s alcohol site.

Consider: 330 ml bottle of beer = 100 ml glass of table wine = 30ml of straight spirits = 10 grams of alcohol = 1 SD. Sex (=0 men ♂, =1 women ♀). Weight: is the body weight in kilograms. Drinking is the drinking period in hours. Calculate EBAC. 

The HTML code is based on Bootstrap, Components, Forms:

<form id="frm1" action="">
  <div class="form-group row">
      <label class="col-sm-2 col-form-label">Sd:</label>
      <div class="col-sm-10">
          <input type="text" id="sd" value="2" class="form-control"  style="text-align:right;">
      </div>
  </div>
  <div class="form-group row">
      <label class="col-sm-2 col-form-label">Sex: </label>
      <div class="col-sm-10">
          <input type="text" id="sex" value="0" class="form-control"  style="text-align:right;">
      </div>
  </div>
  <div class="form-group row">
      <label class="col-sm-2 col-form-label">Weight:</label>
      <div class="col-sm-10">
          <input type="text" id="weight" value="80" class="form-control"  style="text-align:right;">
      </div>
  </div>
  <div class="form-group row">
      <label class="col-sm-2 col-form-label">Drinking:</label>
      <div class="col-sm-10">
          <input type="text" id="drinking" value="2" class="form-control"  style="text-align:right;">
      </div>
  </div>
  <div class="form-group row">
      <div class="col-sm-10">
        <input type="button" onclick="ebac()" value="Submit">
      </div>
  </div>
  <div class="form-group row">
      <label class="col-sm-2 col-form-label"  style="text-align:right;">Result:</label>
      <div class="col-sm-10">
          <input type="text" id="result" value="" class="form-control">
      </div>
  </div>
</form>

Next, let’s see the Javascript code. It should be placed under “/wp-content/themes/your-theme/js/”:

  function ebac(){ // Credits. The formula is taken from [fxSOLVER](https://www.fxsolver.com/), Estimated Blood Alcohol Concentration - EBAC.
      var SD = Number(document.getElementById('sd').value);
      //SD is the number of standard drinks containing 10 grams of ethanol. getElementById() returns the Element object of the specified id ('sd'). elementObject.value return the value property. 
      var BW;
      if (document.getElementById('sex')=="0"){
        // BW is a body water constant (0.58 for men and 0.49 for women)
        BW = 0.58;
      }else{
        BW = 0.49
      }

      // MR is the metabolism rate (0.017).
      MR = 0.017;
      // Wt is body weight (kilogram). The Number() method converts a string value to a number.
      var Wt = Number(document.getElementById('weight').value);
      // DP is the drinking period in hours
      var DP = Number(document.getElementById('drinking').value);
      var EBAC = ( (0.806 * SD *1.2)/(BW*Wt) )-(MR*DP) ;

      document.getElementById('result').value = "Peak blood alcohol concentration: " + EBAC.toString(); // elementObject.value = newValue, set the value property. The toString() method converts a number to a string representation of the number.
  }

Let’s see another example.

The HTML code is based on Bootstrap, too.

<form class="row g-3" action="">
  <div class="col-auto">
    <input class="form-control" id="myresult" type="text">
  </div>
  <div class="col-auto">
    <input onclick="safePassword()" value="Generate password" class="btn btn-primary mb-3"></input>
  </div>
</form>
// It picks or selects random characters from a string. It accepts as arguments the string itself and the desired length of the random substring.
function pick(mystring, length) {
  let result = ' ';
  const mystringLength = mystring.length;
  for ( let i = 0; i < length; i++ ) {
      result += mystring.charAt(Math.random() * mystringLength);
  }

  return result;
}

// It shuffles the characters from a string
function shuffle(array) {
  array = array.split("");
  let currentIndex = array.length, randomIndex, tmp;

  while(currentIndex != 0) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex --;
      tmp = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = tmp;
  }
  return array.join("");
}

// It generates a safe password by using special characters, lowercase and uppercase letters, and numbers and shuffling the characters of the obtained string.
function safePassword(){
  var specials = '[email protected]#$%^&*()_+{}:"<>?\|[];\',./`~';
  var lowercase = 'abcdefghijklmnopqrstuvwxyz';
  var uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var numbers = '0123456789';

  var all = specials + lowercase + uppercase + numbers;

  var password = '';
  password += pick(specials, 2);
  password += pick(lowercase, 2);
  password += pick(uppercase, 2);
  password += pick(numbers, 2)
  password += pick(all, 6);
  password = shuffle(password);
  document.getElementById('myresult').value = password;
}

Create a new theme

/*
 Theme Name:   JustToThePoint
 Description:  Template for JustToThePoint.
 Template:     anawim
 Author:       Maximo Nunez Alarcon (Anawim)
 Author URI:   http://justtothepoint.com
 Version:      1.0
 License:      Copyrighted Wordpress theme
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
*/

/* Mis fuentes */
@font-face {
	font-family: 'PacificoJTTP';
	src: url('../../../fonts/Pacifico.ttf') format('truetype');
}...
/**
 * Enqueue scripts and styles.
 */
function anawim_scripts() {
  wp_enqueue_style( 'anawim-style', get_stylesheet_uri(), array(), _S_VERSION ); /* get_stylesheet_uri() returns the URI for the current theme and wp_enqueue_style enqueues the CSS stylesheet.*/ 
  wp_enqueue_script( 'myJavaScript', get_template_directory_uri() . '/js/miJs.js' ); /* get_template_directory_uri() returns the URI for the current theme.*/
  wp_enqueue_style( 'anawim-FontAwesome', get_template_directory_uri() . '/FontAwesome/css/all.css' ); /* Add Font Awesome fonts.*/
  [...]    
}
add_action( 'wp_enqueue_scripts', 'anawim_scripts' ); /* To enqueue scripts and styles you’ll need to use the wp_enqueue_scripts hook.*/

/* Disable wptexturize in WordPress. For example, __ will be transformed to _ by default. An example would be writing an article about Python: __main__: */
add_filter( 'run_wptexturize', '__return_false' );

/* Let us disable XML-RPC for better WordPress security. */
function removeHeadLinks() {
	remove_action('wp_head', 'rsd_link'); // You don't need it if you do not integrate services like Flickr or JetPack.
	remove_action('wp_head', 'wlwmanifest_link'); // You don't need it if you do not use Windows Live Writer.
        remove_action('wp_head', 'wp_generator'); // Hackers do not need to know your WordPress version.
}
add_action('init', 'removeHeadLinks');

WordPress includes a lot of stuff through the wp_head() hook. The previous code removes:

<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://justtothepoint.com/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://justtothepoint.com/wp-includes/wlwmanifest.xml" />
<meta name="generator" content="WordPress 2.8.4" />
/**
 * Enqueue some JavaScript files only for the post with ID 34585. is_single returns True if the post's ID is '34585'.
 */
function load_js_script() {
  if( is_single('34585') ) { /* If you want to find your Post ID, click on Post, All Posts, and you will find it displayed withing your Posts menu.*/
    wp_enqueue_script( 'js-file', get_stylesheet_directory_uri() . '/js/p5.min.js');
    wp_enqueue_script( 'js-file2', get_stylesheet_directory_uri() . '/js/p5.dom.min.js');
    wp_enqueue_script( 'js-file3', get_stylesheet_directory_uri() . '/js/sketch.js');
    wp_enqueue_script( 'js-file4', get_stylesheet_directory_uri() . '/js/firework.js');
    wp_enqueue_script( 'js-file5', get_stylesheet_directory_uri() . '/js/particle.js');
  }
}
add_action('wp_enqueue_scripts', 'load_js_script');

Add an Author Info Box

The author bio box is a small section at the end of the blog posts, after your post’s content, where you can display information about the post author, show his social media links, website, and more.

You can always use some plugins (Author Bio Box) and you need to provide your WordPress authors’ information (Users, Profile). Let’s create a file template.parts/biography.php and add the following code: (This code is based on wpbeginner.com, How to Add an Author Info Box in WordPress Posts):

    <?php
    global $post;

    // First, we need to check if it is a single post and it has an author.
    if ( is_single() && isset( $post->post_author ) ) {
      // Secondly, we get the post author's display name. get_the_author_meta returns the requested data of the author of the current post.
      $display_name = get_the_author_meta( 'display_name', $post->post_author );

      // If the author does not have a name in WordPress, we get his or her nickname.
      if ( empty( $display_name ) ) $display_name = get_the_author_meta( 'nickname', $post->post_author );

      // Get author's biographical information or description.
      $user_description = get_the_author_meta( 'user_description', $post->post_author );

      // Get author's website URL
      $user_website = get_the_author_meta('url', $post->post_author);

      // Get a link to the author page. get_author_posts_url returns the URL to the author page for the user with the provided ID.
      $user_posts = get_author_posts_url( get_the_author_meta( 'ID' , $post->post_author));

      // Get Author's twitter and Facebook profiles.
      $user_twitter = get_the_author_meta( 'aioseo_twitter', $post->post_author );
      $user_facebook = get_the_author_meta( 'aioseo_facebook', $post->post_author );

      // Now, we are going to display the author's name or nickname.
      if ( ! empty( $display_name ) ) $author_details = '<p class="author_name">About <strong>' . $display_name . '</strong></p>';

      if ( ! empty( $user_description ) )
      // Let's display the author avatar, biography, and posts. get_avatar(user id or email, size -height and width of the avatar image) returns the avatar <img> tag for a user.
        $author_details .= '<p class="author_details">' . get_avatar( get_the_author_meta('user_email') , 70 ) . $user_description . '</p>';

      $author_details .= '<p class="author_links"><a href="'. $user_posts .'">View ' . $display_name . ' posts</a>';

      // Check if the author has a website in his profile.
      if ( ! empty( $user_website ) ) {
      // Display author's website, and his Twitter and Facebook social media links.
          $author_details .= ' | <a href="' . $user_website .'" target="_blank" rel="nofollow"><i class="fa-solid fa-house"></i></a>' . ' | <a href="' . $user_twitter  .'" rel="nofollow" target="_blank"><i class="fa-brands fa-twitter"></i></a> | <a href="'. $user_facebook .'" rel="nofollow" target="_blank"><i class="fab fa-facebook-f"></i></a></p>';
      } else {
      // If the author does not have a website, we just show his twitter and Facebook social media links.
          $author_details .= '<a href="' . $user_twitter  .'" rel="nofollow" target="_blank"><i class="fa-brands fa-twitter"></i></a> | <a href="'. $user_facebook .'" rel="nofollow" target="_blank"><i class="fab fa-facebook-f"></i></a></p>';
      }
  }
  ?>
  <footer class="author_bio_section" ><?php echo $author_details; ?></footer>

Next, we need to decide where to add it. For posts, open your theme or your child theme, and edit single.php as follows (for pages, open page.php). Remember that single.php is the template for displaying our posts:

<?php  
  while ( have_posts() ) : // Start the loop.  
    the_post();  
    get_template_part( 'template-parts/content', get_post_type() ); // It includes the post format-specific template for the content.  
    get_template_part( 'template-parts/biography' ); // We include the author information box.  
    get_template_part( 'template-parts/sharing-box' ); // We include the social share buttons (see next section).  
    showads(); // Google Adsense [...]  

Follow us and share buttons

The idea is quite similar. Let’s create a file template.parts/sharing-box.php and add the following code: (This code is based on FFW.press, How to Add Social Share Buttons by Daan van den Bergh):

<?php

$postUrl = 'http' . ( isset( $_SERVER['HTTPS'] ) ? 's' : '' ) . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; ?>

<section class="sharing-box">
    <h2 class="sharing-box-name">Please Like, Share the knowledge, and comment!</h2>
      <div class="share-button-wrapper">
          <a target="_blank" class="share-twitter" href="https://twitter.com/intent/tweet?url=<?php echo $postUrl; ?>&text=<?php echo the_title(); ?>&via=<?php the_author_meta( 'twitter' ); ?>" title="Tweet this">Tweet this<i class="fab fa-2x fa-twitter"></i></a> 
          // For Twitter, we are going to pass the post's/page's URl, its title and author. the_author_meta outputs the field from the user object in the database.
          <a target="_blank" class="share-facebook" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $postUrl; ?>" title="Share on Facebook">Share on <i class="fab fa-2x fa-facebook-f"></i></a>
    </div> // For Facebook, we only pass the posts/pages URL in href.
</section>
<section class="sharing-box">
  <h2 class="sharing-box-name">Follow us!</h2>
  <div class="mySocialMedia">
    <a target="_blank" href="http://feeds.feedburner.com/Justtothepointcom" class="social-icon-rss"><i class="fa fa-rss fa-2x"></i></a>
    <a target="_blank" href="http://Twitter.com/justtothepoint" class="social-icon-twitter"><i class="fa fa-brands fa-twitter fa-2x"></i></a>
    <a target="_blank" href="https://www.facebook.com/nmaximo7" class="social-icon-facebook"><i class="fa fa-brands fa-facebook fa-2x"></i></a>
    <a target="_blank" href="https://www.pinterest.com/justtothepoint" class="social-icon-pinterest"><i class="fa fa-brands fa-interest fa-2x"></i></a>
    <a target="_blank" href="https://www.pinterest.com/justtothepoint" class="social-icon-instagram"><i class="fa fa-brands fa-instagram fa-2x"></i></a>
    <a target="_blank" href="https://youtube.com/justtothepoint" class="social-icon-youtube"><i class="fa fa-brands fa-youtube fa-2x"></i></a>
  </div>
</section>

Google Adsense and Google Analytics

AdSense is an ad network anyone with a website can join. It enables you to put some ads on your website. Google Analytics is a free web analytics tool or service that provides statistics and help you analyze your website traffic for SEO.

We can use a plugin, add your AdSense code in the header.php and/or footer.php and/or edit functions.php as follows:

function showads() {
    <!‐‐ Your AdSense code goes here. ‐‐>
}

function add_googleanalytics() {
?>
	return '<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXX"></script>
            <script>
            <!-- Your Google Analytics code goes here-->
            </script>'<?php
}
add_action('wp_footer', 'add_googleanalytics');

Observe the presence of the line: add_shortcode(‘adsense’, ‘showads’); in functions.php.

Bitcoin donation

JustToThePoint Copyright © 2011 - 2022 PhD. Máximo Núñez Alarcón, Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.