Category: Uncategorized

  • day 30

    REST API:-

    • Flexibility to build front-end with different technology and using WordPress as back-end.

    This is just a simple GET request to fetch all posts


    The WP CLI:-
    • Command line interface for wordpress
    • We can manage our site, install plugins and many more from cmd only

    example:-

    Adding sidebar widget

    register_sidebar(
    			array(
    				'name'          => __( 'Primary Sidebar', 'screen-time' ),
    				'id'            => 'sidebar-movie',
    				'before_widget' => '<aside id="%1$s" class="widget %2$s">',
    				'after_widget'  => '</aside>',
    				'before_title'  => '<h3 class="widget-title">',
    				'after_title'   => '</h3>',
    			)
    		);
    

    Using dir attribute to change direction of the page to right-to-left
    <html lang="en" dir="rtl">
    

    We use EasyEngine on remote to host the site. To go into our site shell from easyengine use:

    ee shell example.com

    After this we can use the wp CLI commands for our example.com site

    wp user update admin --user_pass="supersecret#23"
  • End of Week 6

    • Lighthouse CLI
    • Page Tempalate
    • Themese and Multisite
    What is Lighthouse?

    Lighthouse is an open-source, automated tool for improving the quality of web pages. You can run it against any web page, public or requiring authentication. It has audits for performance, accessibility, progressive web apps, SEO, and more.

    Basically, we can use the lighthouse to check how our website is performing against some metrics.
    These metrics are:-

    • First Contentful Paint
    • Speed Index
    • Largest Contentful Paint
    • Cumulative Layout Shift
    • Total Blocking Time

    There are multiple ways to use lighthouse, you can check out here. In this blog I will be talking about the CLI only.

    prerequisites:
    • Node LTS and npm must be installed
    • Google chrome installed

    Install the lighthouse node package from npm

    npm install -g lighthouse

    the -g will install it for global use.

    To run audit on your local wordpress site use below command

    lighthouse http://getit.local --view

    Replace the url with your own site, I have set –view as I want to see the results when it is complete.

    Running this will open the chrome browser, run the audit and create a nice report for your site, it will look something like this,

    Explore it using command

     lighthouse --help

    Creating Page template:

    To create a page template we have to add header comment

    &lt;?php
    /*
    Template Name: Movie Replay
    */
    

    Below Code is for a 404 template, that will echo some output if the curent setup is a multisite.

    <?php
    
    get_header();
    
    if (is_multisite()) {
    	_e('We are in a multisite', 'test');
    }
    
    if (is_main_site()) {
    	_e('This is the main site of the network', 'test');
    }
    ?>
    
    
    <div>
    	<?php _e('not found, maybe try searching?', 'test') ?>
    </div>
    
    <?php get_footer();
    ?>
    

  • day 28

    • Can we load multiple style-sheets using one handle?
    • git add .

    To add any css to our theme we have to enqueue it in the functions.php, for that we can use following code

    wp_enqueue_style( 'style', get_stylesheet_uri() );
    

    This will enqueue the main style.css , you can enqueue other scripts too…

        wp_enqueue_style('test-style',get_stylesheet_directory_uri()  . '/gg.css' ) ;
    
    

    Below given are the arguments for this function :- (got it from the core code)

    function wp_enqueue_style( 
        $handle, 
        $src = '', 
        $deps = array(), 
        $ver = false, 
        $media = 'all' ) 
    
    
    • $handle
      • String unique name for the stylesheet
    • $src
      • The source link for the stylesheet
    • $deps
      • array of other handles on which this depends
    • $ver
      • version for stylesheet, if not added WordPress version is used
    • $media
      • the media for which stylesheet has been defined.

    Is it possible to enqueue multiple scripts using same handle?

    • let’s try

    I have this two css files in my theme and the index.php

    This is my code to enquque the stylesheets

    function enqueue_multi()
    {
        wp_enqueue_style('test-style', 
    get_stylesheet_directory_uri()  . '/gg.css') ;
        wp_enqueue_style('test-style', 
    get_stylesheet_directory_uri()  . '/ff.css') ;
    }
    
    add_action('wp_enqueue_scripts', 'enqueue_multi');
    
    

    This is the output coming:-

    **The script enqueue first is not overwritten by the second one**


    Using “git add .” :-

    It is not a good practise to use git add . when adding the changes to the commit, it will add all the changes at the same time even the ones not intended to be pushed.
    Always add the files one by one


  • day 27

    • Flush rewrite in plugin activation
    • WP_Query and the_wp_query

    Why putting flush_rewrite in plugin activation doesn’t work?

    • We are using init hook to register the CPT
    • But the i nit hook is called at very late in the core load

    Then how to do it?

    • Flush them on init hook ?
      • Not the best way, it will flush it at every load.
    • Register the CPT in activation function also, and then flush
      • Good choice as activation will be called only once!

    WP_Query , how the global query works

    • We rarely have to make a custom WP_Query as the wordpress makes one for us.
    • It parses the request url, and fire the query accordingly.
    • Should we overwrite it ?
      • it is safe to use new WP_Query and the loop to temporarily overwrite the global query
      • use reset_post_data() or reset_query() function to reset it though.
    • Maybe you don’t want to create a new query, in my case I just wanted to limit the number of posts per page on the archive page
    • Is it a good idea to create a custom query for this?
    • No, We can do this using the hook pre_get_posts

    Hers’s how i did it

    public function limit_movies_per_page( $query ) {
    		if ( is_post_type_archive( 'rt-movie' ) && $query->is_main_query() ) {
    			$query->set( 'posts_per_page', $this->movies_per_page );
    		}
    	}
    

    And in the constructor I hooked into the pre_get_posts

    		add_action( 'pre_get_posts', [ $this, 'limit_movies_per_page' ] );
    
    

    $this->movies_per_page is a member of my class that can be set to a different value by calling setter.

    1. Can we create a child theme of the existing child theme?

    • No
    • Well I tried it and it didn’t work.

    I might have done something wrong, please suggest if you see in mistake in code. I am using the rtdating theme as parent for this.

  • day 26

    404 page

    If we try to access something that is unavialalbe we are greeted with a 404 page on any site.
    But in wordpress, if we have not created a 404 page explicitly, according to template hierarchy it just shows the index page. It is necessary to have a 404 page for good user experience

    get_search_form() function :

    This function can be used to spawn a search form for wordpress anywhere in our site.
    We can use this in our 404 page, instead of having to create the search form manually.

    <div>
    	<h1><?php esc_html_e("Page Not Found! Maybe try searching?"); ?></h1>
    
    
    <?php
    get_search_form();
    
    ?>
    
    </div>
    

    wp_dropdown_languages() function :

    We can use this function to spawn a select input with all the available languages. It doesn’t look that great but maybe useful to look at its code and see how wordpress processes the language selection This is how it looks in my site.

    The Slider

    The slider component in the theme was complex for me to write code for.
    We can use a mix of CSS and js to show the posters dynamically.
    This is the ugly version of the script I am using to display one slide.

    jQuery(document).ready(function (){
    	const slides = document.getElementsByClassName('the-slide');
    	slides[0].classList.add('active');
    });
    
    
    

    Grids, grids everywhere:-

    Grids in css are a great way to create layout for your site. I have used grid to spawn the movie cards in home page.
    Here is how to create a grid of 3 columns

    
    <style>
    .grid{
    display: grid;
    grid-template-columns: : 1fr 1fr 1fr;
    }
    

    Creating layouts, flexboxes are also used. We can combine both grids and flexboxes, nest them and create some good layouts.

    git : Working on multiple branches at the same time?, don’t forget to check you are on correct branch before commiting.

    How to temporarily save changes and then checkout to other branch (stash)
    $ git stash

    then

    $ git switch the-other-branch

    Once done there you can come back to your earlier branch and get the change by using

    $ git stash apply
  • end of week 5

    Adding custom font to css

    @font-face {
        font-family: big-shoulder;
        src: url('assets/fonts/BigShouldersDisplay.ttf');
    }
    
    .content{
        background-color: rgb(31,31,31);
        font-family: big-shoulder
    }
    

    Home page and Front Page

    • home page is index of our blogs. it’s list of our blogs in reverse chronological order.
    • front page is what users see at home of your site, you can set it to show the index or a static page.

    How to use metadata of post in the loop

    <p>
        <?php echo get_post_meta(get_the_ID(), 'rt-movie-meta-basic-release-date', true); ?>
    </p>
    <p>
        <?php echo get_post_meta(get_the_ID(), 'rt-movie-meta-basic-content-rating', true); ?>
    </p>
    <p>
        <?php echo the_terms(get_the_ID(), 'rt-movie-genre')[0]->name ?>
    </p>
    

    How to register menu locations in theme?

     register_nav_menus(
            array(
            'header-menu' => __('Header Menu'),
            'footer-menu-1'  => __('Footer Menu 1'),
            'footer-menu-2' => __('Footer Menu 2'),
            )
        );
    

    Using it in template

     <div class="secondary-menu-container">
            <?php wp_nav_menu(['menu'=>'footer-menu-2']); ?>
        </div>
    

    Namespace naming standards

    • camelcase
      • example : theMovieLibrary
    • upper camelcase/ pascal case
      • example : TheMovieLibrary

    3 ways to reset wp_query, which one to use where?

    1. rewind_posts() : not modifying the query just want to reset the post at begin
    2. wp_reset_query() : Using wp_reset_query() restores the WP_Query and global $post data to the original main query. You MUST use this function to reset your loop if you use query_posts() within your loop.
    3. wp_reset_postdata : Use wp_reset_postdata() when you are running custom or multiple loops with WP_Query. This function restores the global $post variable to the current post in the main query. If you’re following best practices, this is the most common function you will use to reset loops.

  • approaching theme development….

    • Things covered today
    • Where to begin

    Things Covered Today


    The loop:

    • We don’t have to query again to get posts because the main query almost always has the data we require.
    • To loop through this we use below code
    <?php
    if(have_posts()){
      while(have_posts()){
    the_post() //update the global post
    echo the_title();
    } //endwhile
    }else{
    echo "Sorry, no post found";
    }
    

    Why the the_post() is required ? well I forgot to call it and the while loop become infinite. This function sets up the next post in the loop so if we don’t call it then we will go into infinite loop.

    Can we have multiple loops?

    • Yes, on a page we may have a use case to create multiple loops to access the posts like on home page we want to show trending and upcoming both posts. For that we can use multiple loops and also custom query.
    • Here is a good example of how to use multiple loops:-
    <?php
    // Start the main loop
    if ( have_posts() ) :
        while ( have_posts() ) : the_post();
            the_title();
        endwhile;
    endif;
    
    // Use rewind_posts() to use the query a second time.
    rewind_posts();
    
    // Start a new loop
    while ( have_posts() ) : the_post();
        the_content();
    endwhile;
    ?>
    

    ! It is important that we reset the posts after each loop, without it will give unexpected results.

    Here are 3 ways we can reset the post query
    1. using rewind_posts()
    2. using wp_reset_postdata()
    3. using wp_reset_query()

    Template tags that can be used inside loop

    the_author()
    the_category()
    the_content()
    the_excerpt()
    the_ID()

    Common Conditional Tags for templates

    is_home()
    is_admin()
    is_page()
    is_single()
    is_author()

    Well we are almost 10% there to start building our theme so let’s begin.

    Where to begin?


    We are now equipped with some knowledge on how themes work in WordPress and now it is time to build one for our assignment.

    For people like me who don’t like fron-tend much here’s how I apporach:-

    • Look at the codebase of themes already built
      • the twentytwnety theme series is a good start to look at how the themes code look like
    • Start with just a button
      • Sometimes we hate to do something because we haven’t tried it for long enough.
      • Start with just a button, make it to your liking and build from there.
    • Start writing HTML
      • Just start writing some HTML, use the template tags and conditionals in WordPress to maybe just list the titles of the post and take it further from there.

    For reference Here’s how my index.php and style.css looks now:

    <?php
    while (have_posts()){
    	the_post();
    	the_post_thumbnail([40,40]);
    	the_title('<h2>', '</h2>');
    	the_excerpt();
    
    }
    ?>
    
    /*
    Theme Name: Screen Time
    Description: Theme for managing movies.
     */
    
    body{
        background-color: rgb(255,105,180);
        color: black;
        margin: 0px;
    }
    

  • day 23, themes

    • functions.php
    • Common template tags
    • Creating a page template

    functions.php file

    The functions.php file inside any theme directory can be used to write code that is necessary for the theme like enqueuing styles and scripts.

    We can also load our textdomain in this file, and add theme support. Below is a sample functions.php file that loads the textdomain

    <?php
    /**
     * Function to set up the screen time theme.
     */
    function screen_time_setup(){
    //Make theme available for translation
    	load_theme_textdomain( 'screen-time', get_template_directory() . '/languages' );
    }
    ?>
    

    we can hook this function into the ‘after_theme_setup’ hook

    add_action( 'after_setup_theme', 'screen_time_setup' );
    
    

    Common Template Tags

    1: get_header() : loads header template

    2: get_footer(): loads footer template

    3: get_sidebar(): loads sidebar template

    …wait, I am not going to list all tags here, here is how you can find the general tags by yourself

    Open public directory of your site, inside that go to “wp-includes” directory and find “general-template.php”, this files has all the general tags with nice documentation

    Creating Page Template

    We can create our own page template for that

    Create a file name it anything like mytemp.php, we don’t have to name it like page-mytemp.php

    <?php /* Template Name: MY Template */ ?>
    

    We can customize this template according to use case and then use it when creating new page.

  • day 22

    • Debug Config
    • Template Hierarchy
    • Tables in multisite

    Before starting with debugging we have to first define this constants in the wp-config.php file

    define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );   // WP 5.2 and later
    define( 'WP_DEBUG', true );
    define( 'WP_DEBUG_DISPLAY', false );
    define( 'WP_DEBUG_LOG', true );
    

    Template Hierarchy


    WordPress uses templates to display content and there can be many templates depending on the use case for custom post types archives we can create templates and then for a single movie, we can create a template.

    But, for creating a theme we need only one files index.php, so in wordpress template hierarchy index.php is the last one so if no template is found then at last index.php is used.

    Learning about template hierarchy is important as we can then use it to make our own templatates for like custom post types or archive etc

    Tables in Multisite

    When creating a multisite installation of wordpress, few extra tables are added along with default tables.

    • wp_site
    • wp_sitemeta
    • wp_signups
    • wp_blogs
    • wp_blogmeta
    • wp_registration_log
    Single Installation
    Multisite Installation
  • day 21

    • Themes : Do we really need just two files?
    • Themes vs Plugins
    • Query Monitor Plugin

    Themes in wordpress


    After plugin, it is now time to learn about themes, unlike plugins themes do not add any extra functionality to WordPress but change how the site looks.

    Having a good theme that matches with out site intention and goal is must for anyone creating site using WordPress. There are many free themes available but we can also choose to develop our own.

    To start with theme development we need to create two files

    • style.css
    • index.php

    It is not mandatory to keep all you styles and style.css, we can use other organized structure for that but like how in plugin we used the index.php header to let the WordPress know about our plugin, we use the style.css header for theme info

    /*
    Theme Name: Test Theme
    Theme URI: tr.rt.gw
    Author: Me
    Author URI: me.com
    Description: Testing theme
    Version: 0.0.1
    Requires at least: 5.0
    Requires PHP: 7.0
    License: GNU General Public License v2 or later
    License URI: http://www.gnu.org/licenses/gpl-2.0.html
    Text Domain: test-theme
    */
    

    I am using paimo chair theme for this site.

    Theme vs Plugins


    Themes are for representation of our site, its look etc. Plugins we use to add extra functionality.

    We should never use themes to add critical features, always use plugins for that as the official docs suggest. Combined together theme and plugin can really make a very good site like the one we will be making in our course.


    Query Monitor Plugin


    Query monitor plugin is a developer tool we can use to see the database queries our wp site is making. We can use it for debugging our site.

    Not only db queries it can show you PHP errors, API calls, ajax calls, scripts enqueued etc.

    I found it very useful as on my own site, the script was not getting loaded and I couldn’t figure out why.

    We can download the zip for plugin from here

    “Our plugin needs a lot of rework to be done for it to become fully functional and deployable.”