wordpress cheatsheet

wordpress cheatsheet link: https://docs.google.com/document/d/15gRGAB57iEFs_TGsqrk08_OZ36mX1yfsMKCYM6qX7gk/edit?usp=sharing



We can develop our custom theme in wordpress. Let’s first understand the folder structure of wordpress.


So, when you creating a new theme for your wordpress site, make sure you have putted 2 files inside /wp-content/themes/your-theme-name

Files: style.css, screenshot.png/.jpg & index.php

Now style.css contains information about this theme which we are going to develop.


Style.css

/*

Theme Name: My Theme

Description: This is a custom theme

Author: Shimanta Das

*/


Now you can see below in our wordpress dashboard  “Appearance -> Theme”


Topic: initialise .css and .js  & images files for wordpress theme

First of all download a html/bootstrap theme from a site. Ex: https://themewagon.com/themes/free-bootstrap-5-digital-marketing-agency-template-growmark/


 When you want to link those files you should use a function as “get_template_directory_uri()”. Let’s see an example below:

before

 <link href="style.css" rel="stylesheet">

after

 <link href="<?php echo get_template_directory_uri(); ?>/style.css" rel="stylesheet">


Using the function “get_template_directory_uri()” helps to get the path of the current installed theme.


Note: in wordpress hierarchy, by default it is called “front-page.php”. But if it can’t found then it calls “index.php”

When you are working on wordpress theme development, you should use “wp_header()” and “wp_footer()” functions. If you enable “wp_footer()“ so it will enable wordpress admin bar.




Topic: enqueue scripts

We can invoke scripts inside the theme without using header and footer php. Let’s see a code sample where we can invoke scripts in functions.php file.

// enque css scripts

function prefix_enqueue_styles() { 

  wp_enqueue_style('bootstrap_css', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '4.5.0');

  wp_enqueue_style('fontawesome_css', get_template_directory_uri() . '/css/fontawesome-all-min.css', array(), '5.15.3');

  wp_enqueue_style('slick_css', get_template_directory_uri() . '/css/slick.css', array(), '1.8.1');

  wp_enqueue_style('slick_theme_css', get_template_directory_uri() . '/css/slick-theme.css', array(), '1.8.1');

  wp_enqueue_style('custom_css', get_template_directory_uri() . '/css/custom.css', array(), '1.0');

}

add_action( 'wp_enqueue_scripts', 'prefix_enqueue_styles' );



// enque js scripts

function prefix_enqueue_scripts() {

  wp_enqueue_script('jquery_js', get_template_directory_uri() . '/js/jquery.min.js', array(), '3.5.1', true);

  wp_enqueue_script('bootstrap_bundle_js', get_template_directory_uri() . '/js/bootstrap.bundle.min.js', array('jquery_js'), '4.5.0', true);

  wp_enqueue_script('slick_js', get_template_directory_uri() . '/js/slick.min.js', array('jquery_js'), '1.8.1', true);

  wp_enqueue_script('fontawesome_all_js', get_template_directory_uri() . '/js/font-awesome-all.min.js', array(), '5.15.3', true);

  wp_enqueue_script('custom_js', get_template_directory_uri() . '/js/custom.js', array('jquery_js'), '1.0', true);

}

add_action( 'wp_enqueue_scripts', 'prefix_enqueue_scripts' );




Topic: include custom header and footer

First make a “header.php” and cut the code from <!DOCTYPE html> up to  navbar.

Now paste the code inside “header.php” and now call that file inside “index.php”

Now include the “header.php” file inside “index.php” then call using the “get_header()” function.


Now let’s assume you have more than one “header.php” file in your theme, then how should you call them ?

Say I have 3 files in wordpress theme, Ex: header.php, header-contact.php, header-offer.php

When you call  <?php get_header(); ?> you generally call by default “header.php”.

But for calling ’header-contact.php’, ‘header-offer.php’ just use: 


<?php get_header(‘contact’); ?>

Automatically calls header-contact.php file

<?php get_header(‘offer’); ?>

Automatically calls header-offer.php file


Note: same analogy will be applied for footers too. You should create a “footer.php” and then cut the footer part to the last </html> tag and paste into the file. Now for calling the file simply use the “get_footer()” function. 


Note: we should call the wp_head(); inside after <head> tag in ‘header.php’ and we should call wp_footer(); inside </body> tag in ‘footer.php’

 


Topic: how to create menus in wordpress theme

For adding a menu option to the theme just add ‘Primary Menu’ and give it a value as ‘Top Menu’ and you will see the option in appearance.

<?php

register_nav_menus(

array(

'primary-menu'=>'Top Menu'

)

)

?>


Now let’s create and add pages inside the menu. After that I called this..

<?php

wp_nav_menu(array(‘theme_location’=>'primary-menu', ‘menu_class’=>’something’))

?>


Trick: let’s catch up with some short cart tricks.

So I have created a manu called “mobile-menu” and added some pages inside it.

<ul class="mobile-menu-only">

  <?php

                                    wp_nav_menu(array(

                                    'menu' => 'mobile-menu',

                                    'container' => false,

                                    'items_wrap' => '%3$s'

                                    ));

                                ?>

                            </ul>


One thing to note, when you use ‘items_wrap’ you generally remove <ul> tags.



Topic: add css classes to <li> and <a> tags using wp_nav_menu()

Let’s see first HTML part of wp_nav_menu

<div class="collapse navbar-collapse offset" id="navbarSupportedContent">

   <ul class="nav navbar-nav menu_nav ml-auto">

   <?php

   wp_nav_menu(array('menu'=>'Navbar-Menu','container'=>'false', 'items_wrap' => '%3$s',));

    ?>

 </ul>

 </div>


Let’s see functions.php

// add classes to <a> tags inside <li> tags

function add_menu_link_class($atts, $item, $args)

{

    $atts['class'] = 'nav-link';

    return $atts;

}

add_filter('nav_menu_link_attributes', 'add_menu_link_class', 1, 3);


// add classes to <li> tags

function _namespace_menu_item_class( $classes, $item ) {       

    $classes[] = "nav-item"; // you can add multiple classes here

    return $classes;

add_filter( 'nav_menu_css_class' , '_namespace_menu_item_class' , 10, 2 );




Topic: how to display pages in wordpress on call

First make a file as “page.php” and follow the below skeleton structure

If you want to know the page name then simply use function: the_title() 

Note: if you want to get the project’s url then simply use: site_url()


Your page.php will look like…

<?php get_header(); ?>

<?php get_footer(); ?>


But for showing content of “page.php” simply use the “the_content()” function.


Topic: enable featured/thumbnail image.

When you are working on a custom theme, sometimes you do not show the option of featured image. To enable this just add a function inside the “functions.php” file.

<?php add_theme_support(‘post-thumbnails’) ?>


To get the thumbnail image of a page or post …

<?php wp_get_attachment_image_src(get_post_humbnail_id(),’small/medium/custom’) ?>



Topic: how to set up a header image for a wordpress site.

First of all we need to enable the header image option. For this add a function in the “functions.php”.

“add_theme_support(‘custom-header’);”


After that you will get the “Menus” option inside the “Appearance” tab.


You will also find an option as “Header Image”, where you can set the header image.

 


Now for calling the header image use the function, get_header_image()



Topic: set site logo in wordpress

Note: if you want to set favicon of your wordpress site, then use function - get_site_icon_url()

see below code sample: 

<!--favicon-->

  <link rel="icon" type="images/favicon.png" href="<?php echo get_site_icon_url(); ?>">


Topic: set custom template page template

When you create a wordpress site from an HTML theme, whenever you create and call a page it’s always called via “page.php”. But in the page.php we can’t set a custom template which will be applicable for a particular page.

Let’s install a plugin named as “classic editor”

For example, we need to set a “contact us” page. First create a “contact us” page from wordpress admin. Now, let’s make a file called “template-contact.php”.

Now let’s add the short-code in this file.

<?php 

/**

 * Template Name: contact us

 */

 get_header();

?>


 your content


<?php get_footer(); ?>


Alternative video: https://www.youtube.com/watch?v=q777alqFa0Y


Note: when you make template pages, make sure to include under ‘templates/’ names folder and paste all the files here. Make name using /*Template Name: your-set-name */


Topic: current active page css class

When you working on custom template of wordpress you might find a class as “current_page_item”

This class is applicable if the current item is a page and it’s in active condition.

Note: you will also find a class as “current_menu_item”. It's applicable for many use cases like page, post, archive etc. if it’s in active condition.



Topic: create posts and show the number of posts in the “blogs” page.

In wordpress we can create posts and display them. But one thing to note:

Every “posts are posts” and ”every pages are posts”, just the thing for posts:type=’posts’ and for pages type=’pages’.


Step 1: create posts by wordpress admin.

Step 2: go to the desired file ex: “first-page.php” or “index.php” or “template-blogs.php”

Step 3: now for getting all the posts where their type=“posts”

<!-- post loop start -->

            <?php

            $args = array(

                'posts_per_page' => -1,

                'offset' => 0,

                'orderby' => 'date',

                'order' => 'ASC',

                'post_type' => 'post',


            );

            $wq = new WP_Query($args);

            if ($wq->have_posts()):

                while ($wq->have_posts()):

                    $wq->the_post();

                    $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium');

                    ?>

                    <div class="col-lg-4 col-sm-6">

                        <div class="single-blog-grid">

                            <a href="#">

                                <figure>

                                    <img src="<?php echo $thumbnail[0]; ?>" alt="" />

                                </figure>

                                <figcaption class="text-white">

                                    <h3><?php echo the_title(); ?></h3>

                                    <p class="white-dash"><?php echo get_the_date(); ?></p>

                                </figcaption>

                            </a>

                        </div>

                    </div>

                <?php endwhile; endif; 

wp_reset_postdata(); 

?>

                    <!-- post loop end -->


Note: when you make template pages, make sure to include under ‘templates/’ names folder and paste all the files here. Make name using /*Template Name: your-set-name */

If you want to skip any post in page, the use the code … 'post__not_in'=> [get_the_ID()] 



Topic: Create post type by services

In wordpress theme development, We see the posts types generally by either ‘posts’ or ‘pages’. Let’s create a post type by ‘services’.


Open “functions.php” and paste the below code

// adding custom post type - 

function custom_post_type_services() {

    $supports = array(

    'title', 

    'editor', 

    'author',

    'thumbnail', 

    'excerpt', 

    'custom-fields', 

    'comments',

    'revisions', 

    'post-formats',

    );

    $labels = array(

    'name' => _x('services', 'plural'),

    'singular_name' => _x('services', 'singular'),

    'menu_name' => _x('services', 'admin menu'),

    'name_admin_bar' => _x('services', 'admin bar'),

    'add_new' => _x('Add New', 'add new'),

    'add_new_item' => __('Add New services'),

    'new_item' => __('New services'),

    'edit_item' => __('Edit services'),

    'view_item' => __('View services'),

    'all_items' => __('All services'),

    'search_items' => __('Search services'),

    'not_found' => __('No services found.'),

    );

    $args = array(

    'supports' => $supports,

    'labels' => $labels,

    'public' => true,

    'query_var' => true,

    'rewrite' => array('slug' => 'services'),

    'has_archive' => true,

    'hierarchical' => false,

    );

    register_post_type('services', $args);

    }

add_action('init', 'custom_post_type_services');


After adding this you will find a section as “services” in wordpress admin panel.


For showing service’s post … I will create a “template-services.html”

<?php

            $args = array(

                'posts_per_page' => -1,

                'offset' => 0,

                'orderby' => 'date',

                'order' => 'ASC',

                'post_type' => 'services',


            );

            $wq = new WP_Query($args);

            if ($wq->have_posts()):

                while ($wq->have_posts()):

                    $wq->the_post();

                    $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium');

                    ?>

                    <!-- services start -->

                        <div class="col-lg-4 col-md-6 service-col">

                            <div class="single-blog-grid service-grid">

                                    <figure>

                                        <img src="<?php echo $thumbnail[0]; ?>" alt=""/>

                                    </figure>

                                    <figcaption class="text-white service_cnt_wrap">

                                        <h3><?php echo the_title(); ?></h3>

                                        <p>

                                        <?php echo get_the_excerpt(); ?>

                                        </p>

                                        <a href="#">Read More</a>

                                    </figcaption>

                            </div>

                        </div>

                        <!-- servives end -->

                        <?php endwhile; endif; ?>


Helpful doc:https://www.cloudways.com/blog/wordpress-custom-post-type/


Topic: show custom post type in wordpress.

If you create a custom post type, ex: services and create several posts under it. Then for displaying a single post we use the_permalink() function.

For displaying a single post we use a file named “single-post_type.php”



Topic: pagination

We can apply pagination when we work with custom HTML templates. I have apply pagination for custom post type in a page named as ‘templates/reviews.php’


reviews.php

<section class="review-sec common-padd">

        <div class="container">

            <div class="row">

                <div class="col-lg-23">

             


                    <?php

                    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;


                    $args = array(

                        'posts_per_page' => 3,

                        'post_type' => 'reviews',

                        'paged' => $paged,

                    );

                    $wq = new WP_Query($args);

                    if ($wq->have_posts()):

                        while ($wq->have_posts()):

                            $wq->the_post();

                            $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium');

                            ?>


                            <div class="review-box">

                                <div class="icon-wrap">

                                    <img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/testimonial-icon.png">

                                </div>

                                <h2><?php echo esc_html(get_the_content()); ?></h2>

                                <div class="user-wrap">

                                    <img src="<?php echo esc_url(get_field('user_profile_image')); ?>">

                                    <div class="user-info">

                                        <h5><?php echo esc_html(get_field('users_name')); ?></h5>

                                        <p><?php echo esc_html(get_field('user_designation')); ?></p>

                                    </div>

                                </div>

                            </div>


                        <?php endwhile; ?>


                        <div class="pagination-wrap">

                            <?php 

                             echo paginate_links(array(

                                'base' => get_pagenum_link(1) . '%_%',

                                'format' => 'page/%#%/',

                                'total' => $wq->max_num_pages,

                                'current' => max(1, $paged),

                                'show_all' => false,

                                'end_size' => 1,

                                'mid_size' => 2,

                                'prev_next' => true,

                                'prev_text' => __('<i class="fa-solid fa-arrow-left"></i>','test'),

                                'next_text' => __('<i class="fa-solid fa-arrow-right"></i>','test'),

                                'type' => 'list',

                             ));

                            ?>

                

                </div>



                    <?php endif;

                    wp_reset_postdata();

                    ?>

                </div>

            </div>

        </div>

    </section>


Let’s see the html part of these … 

<div class="pagination-wrap">

                    <ul>

                        <li class="arrow"><a href="#"><i class="fa-solid fa-arrow-left"></i></a></li>

                        <li><a href="#">1</a></li>

                        <li><a href="#">2</a></li>

                        <li><a href="#">3</a></li>

                        <li>...</li>

                        <li><a href="#">10</a></li>

                        <li class="arrow"><a href="#"><i class="fa-solid fa-arrow-right"></i></a></li>

                    </ul>

                </div>


Let’s see a custom.css file for this…

.pagination-wrap {

    padding: 30px 0 0;

}


.pagination-wrap ul {

    display: flex;

    align-items: center;

    margin: 0;

    padding: 0;

    list-style: none;

    justify-content: center;

}


.pagination-wrap ul li {

    width: fit-content;

    padding: 0 10px;

    font-size: 24px;

    font-weight: 700;

}


.pagination-wrap ul li a {

    width: 60px;

    height: 60px;

    border-radius: 50%;

    display: flex;

    justify-content: center;

    align-items: center;

    border: 2px solid var(--orange);

    color: var(--black);

    font-weight: 700;

    font-size: 24px;

    background: var(--white);

}


.pagination-wrap ul li a:hover {

    background: var(--orange);

    color: var(--white);

}


.pagination-wrap ul li.arrow a {

    border: 1px solid #E9E9E9;

}


@media only screen and (max-width: 767px) {

  .pagination-wrap ul li {

        display: none;

    }


    .pagination-wrap ul li.arrow {

        display: block;

    }

}


But when you apply wordpress pagination it by defaults generates <span> tags for active page , so we need to apply custom css effect for that too .

.pagination-wrap ul li span {

    width: 60px;

    height: 60px;

    border-radius: 50%;

    display: flex;

    justify-content: center;

    align-items: center;

    border: 2px solid var(--orange);

    color: var(--black);

    font-weight: 700;

    font-size: 24px;

    background: var(--white);

}


.pagination-wrap ul li span:hover {

    /* background: var(--grey);

    

    color: var(--white); */

}


.pagination-wrap ul li.arrow span {

    border: 1px solid #E9E9E9;

}



Note: ‘offset’ should be added when applying this custom pagination.



Topic: how to display single post with details -  post display

For showing a post details into a particular page you should make a file as “single.php”

For this in the details page ex:blog details, we need to configure “the_permaink()” it will automatically generate blog details according to permalink()

template-blogs.php

<a href="<?php the_permalink(); ?>">view more</a>


single.php

<?php the_post(); ?>

<div class="col-lg-12">

                                <?php $path = wp_get_attachment_image_src(get_post_thumbnail_id(),'small'); ?>

                                <div class="blog_feature_thumnb"> <img src="<?php echo $path[0]; ?>"></div>

                                <div class="blog_feature_content"> 

                                        <h2><?php echo the_title(); ?></h2>

                                      <br>

<h4><?php echo the_author(); ?></h4>

                                             <br>

                                   <h4><?php echo get_the_date(); ?></h4>

<br>

<p>

                                           <?php echo the_content(); ?>     

                                        </p>

                                </div>



Topic: comment form

We can apply a comment form in our post. For that we need to apply a function: <?php echo  comment_form(); ?>


We can apply custom css style too for that we need to pass args into comment_form().

<div class="row">

        <div class="col-1"></div>

        <div class="col-10">

            <?php

            $comment_args = array(

                'class_submit' => 'btn btn-default submit',

                'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x('Comment', 'noun') . '</label> <textarea id="comment" name="comment" class="form-control" cols="45" rows="8" aria-required="true" required="required"></textarea></p>',

                'fields' => array(

                    'author' => '<p class="comment-form-author">' . '<label for="author">' . __('Name') . ($req ? ' <span class="required">*</span>' : '') . '</label> ' .

                        '<input id="author" name="author" class="form-control" type="text" value="' . esc_attr($commenter['comment_author']) . '" size="30"' . $aria_req . $html_req . ' /></p>',

                    'email' => '<p class="comment-form-email"><label for="email">' . __('Email') . ($req ? ' <span class="required">*</span>' : '') . '</label> ' .

                        '<input id="email" name="email" class="form-control" ' . ($html5 ? 'type="email"' : 'type="text"') . ' value="' . esc_attr($commenter['comment_author_email']) . '" size="30" aria-describedby="email-notes"' . $aria_req . $html_req . ' /></p>',

                    'url' => '<p class="comment-form-url"><label for="url">' . __('Website') . '</label> ' .

                        '<input id="url" name="url" class="form-control" ' . ($html5 ? 'type="url"' : 'type="text"') . ' value="' . esc_attr($commenter['comment_author_url']) . '" size="30" /></p>',

                )

            );

            echo comment_form($comment_args); ?>

        </div>

        <div class="col-1"></div>

    </div>


Topic: comment list

After making the comment form it’s time to display all the comments. For that we need to use a built-in function called “comment_template()”.

<?php comments_template(); ?>


After using this it lists all the submitted comments for that post and also calls the “comment_form()” function too.


Note: generally you do not get the css style so I added it into “custom.css” file.

/* comment list css */

.commentlist {

    list-style: none;

    padding: 0;

}

.comment {

    margin-bottom: 20px;

    padding: 10px;

    border: 1px solid #ccc;

}

.comment .comment-author {

    font-weight: bold;

}

.comment p {

    margin: 10px 0;

}

.comment .reply {

    margin-top: 10px;

}

.comment-respond {

    margin-top: 30px;

}

.comment-form input[type="text"],

.comment-form textarea {

    width: 100%;

    padding: 10px;

    margin-bottom: 10px;

    border: 1px solid #ccc;

    border-radius: 5px;

}

.comment-form input[type="submit"] {

    background-color: #007bff;

    color: #fff;

    border: none;

    padding: 10px 20px;

    cursor: pointer;

    border-radius: 5px;

}

.comment-form input[type="submit"]:hover {

    background-color: #0056b3;

}



Topic: Fetch posts related to category

If you want to fetch posts by category, then make a file as “category.php” and put the below code … 

<!-- post loop start -->

            <?php

            

            if (have_posts()):

                while (have_posts()):

                    the_post();

                    $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium');

                    ?>

                    <div class="col-lg-4 col-sm-6">

                        <div class="single-blog-grid">

                            <a href="#">

                                <figure>

                                    <img src="<?php echo $thumbnail[0]; ?>" alt="" />

                                </figure>

                                <figcaption class="text-white">

                                    <h3><?php echo the_title(); ?></h3>

                                    <p class="white-dash"><?php echo get_the_date(); ?></p>

                                <br>

                                </figcaption>

                            </a>

                        </div>

                        <b>

                        <a href="<?php the_permalink(); ?>">view more</a>

                       </b>

                    </div>


                <?php 

            endwhile; 

            endif; 

            ?>

                    <!-- post loop end -->

 

Topic: enable sidebar/widgets for theme

To enable the sidebar in wordpress admin, you should first register this sidebar. 

register_sidebar(array(

‘name’=>’set name’,

‘id’=>’set a unique name’,

));



After this it will show a “widgets” option in the admin panel.

 


In the “functions.php“

// enable widgets option in sidebar wordpress admin

register_sidebars(array(

    'name'=>'custom sidebar',

    'id'=>'sidebar',

));


Now inside this thing inside like ‘template-blogs.php’

<?php dynamic_sidebar('sidebar'); ?>


Note: when you call sidebar you can call using “get_sidebar(‘sidebar-name’)”.


Topic: set the title of page/website

So we can set the website all pages title using function: 

bloginfo(‘name’)

We can get the tagline also by using 

bloginfo(‘description’)


Topic: set 404 page

For settings 404 - not found page inside wordpress, we need to create a page as “404.php”


Topic: Get the category listing

We can get all the categories by the “get_categories()” function and it will return a php array.

We can get the category link by using, “get_category_link($cat->termid)”. Follow the below code …

<?php 

    $categories = get_categories();

    foreach($categories as $category) {

       echo '<div class="col-md-4"><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a>'.$category->count.'</div>';

    }

    ?>


Topic: excerpt text support

sometimes you might find an excerpt text option in post, then you can use this function…. add_post_type_support( ‘page’, ‘excerpt’ ); 


Topic: taxonomy 

In WordPress, taxonomy refers specifically to a system for classifying and organizing your content. It's like a filing cabinet for your website's posts, pages, or custom post types.

In simple words, we can say the category is also a type of taxonomy. we found a category inside the “post” option in wordpress admin.

In post taxonomy becomes like: http://localhost/site6/wp-admin/edit-tags.php?taxonomy=category

If we create a custom taxonomy then it may becomes: http://localhost/site6/wp-admin/edit-tags.php?taxonomy=service_category&post_type=services


Let’s see the code on how to create a custom taxonomy.

// custom taxonomy creation - functions.php

function register_custom_taxonomy()

{

    $labels = array(

        'name'              => _x('Categories', 'taxonomy general name'),

        'singular_name'     => _x('Category','taxonomy singular name'),

        'search_items'      => __('Search Category'),

        'all_items'         => __('All Category'),

        'parent_item'       => __('Parent Category'),

        'parent_item_colon' => __('Parent Category:'),

        'edit_item'         => __('Edit Category'),

        'update_item'       => __('Update Category'),

        'add_new_item'      => __('Add New Category'),

        'new_item_name'     => __('New Category Name'),

        'menu_name'         => __('Categories'),

    );


    $args = array(

        'hierarchical'      => true, 

        'labels'            => $labels,

        'show_ui'           => true,

        'show_admin_column' => true,

        'query_var'         => true,

        'show_in_rest' => true,

        'rewrite'    => array('slug' => 'service_detail'),

    );


    register_taxonomy('service_category', 'services', $args);

}

add_action('init', 'register_custom_taxonomy');


Here are 2 things that should be understood… ‘service_category’ is the name of a taxonomy which will be generated against post type ‘services’. When you click on any post related to ‘service_category’ it will open browser url inside ‘service_detail’ 



Topic: how to filter/shows taxonomy posts

Here I will guide you on how to display posts depending upon taxonomy. Let’s assume a scenario where we are building a project, where we have services-> online and offline services. We have relevant posts regarding those. But customers may select one category to show posts against that.


We have 2 files - “template-service.php”, “taxonomy-service_category.php” and “functions.php”. Inside the service's page I have listed down all the codes…. 


template-service.php

<?php 

      $values = get_terms('service_category');

                    foreach ($values as $term) {

                        echo "<a href='" . get_term_link($term) . "'>" . $term->name . "</a><br>";

                    }

                    ?>



taxonomy-service_category.php

<div class="row">

    <?php

    if (have_posts()):

        while (have_posts()):

            the_post();

            $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium');

            ?>

            <!-- services start -->

            <div class="col-lg-4 col-md-6 service-col">

                <div class="single-blog-grid service-grid">

                    <figure>

                        <img src="<?php echo $thumbnail[0]; ?>" alt="" />

                    </figure>

                    <figcaption class="text-white service_cnt_wrap">

                        <h3><?php echo the_title(); ?></h3>

                        <p>

                            <?php echo get_the_excerpt(); ?>

                        </p>

                        <a href="<?php the_permalink(); ?>">Read More</a>

                    </figcaption>

                </div>

            </div>

            <!-- servives end -->

        <?php endwhile; endif; ?>


</div>



Topic: custom forms fields - ACF

We can make dynamic form’s fields in our wordpress site. For that we will use a plugin called ACF. you can manually download from plugins or also use a PRO version.


Let’s first install or shift the zip folder to wp-incldes/plugin folder.

Note: linked peculiar page with the form group. Always use ‘get_field’ instead of ‘the_field’.


Now enter data manually, ex: contact us.


Now in the contact us page i see url looks like: http://localhost/site6/wp-admin/post.php?post=18&action=edit


So, now for adding custom form fields in the template page use, 

<p><a href=""> <?php get_field('phone', 18); ?>    </a></p> 

Here ‘phone’ is the field name, which is mentioned in the form group and post id ‘18’.




Topic: how to apply repeater in ACF

We can apply an ACF repeater when we need to apply some fields which will be repeated. For example: in courses we have several courses which will be repeated but their data will change.


Step 1: first make a repeater field and mention its name. It will be required when you call the repeater name.


Step 2: now add the custom sub-field under that.


For calling the acf repeater field use the following codeblock…

<?php

if( have_rows('repeater_field_name') ):

    while( have_rows('repeater_field_name') ) : the_row();

        $sub_value = get_sub_field('sub_field');


    endwhile;

else :

    // Do something...

endif;


Note: we can set ACF fields for custom post type too.


Now you can directly fetch ACF field data against that related post. See below code … 


<h2> <?php echo get_field('service_details_title'); ?> </h2>

                            <p class="pink-dash"> <?php echo get_field('service_details_mini_text'); ?>  </p>


One thing to note, we can pass the post ID in the acf repeater field. Let’s see how … 

<?php

            if (have_rows('home_footer_widgets_items',19)):

                while (have_rows('home_footer_widgets_items',19)):

                    the_row();

                    $name = get_sub_field('home_footer_widgets_item_name');


For more visit docs: https://www.advancedcustomfields.com/resources/have_rows/




Topic: contact form 7

We can make contact forms using this plugin. 


Form modified code looks like…

<div class="row">

                                               <div class="col-lg-6">

                                                <div class="form-group">

[text text-328 class:form-control placeholder "Name"]

</div>

                                               </div>

                                               <div class="col-lg-6">

                                                <div class="form-group">

[email email-301 class:form-control placeholder "Email"]

</div>

                                               </div>

                                               <div class="col-lg-6">

                                                <div class="form-group">

[tel tel-245 class:form-control placeholder "Phone"]

</div>

                                               </div>

                                               <div class="col-lg-6">

                                                <div class="form-group">

[text text-328 class:form-control placeholder "Subject"]

</div>

                                               </div>

                                               <div class="col-lg-12">

                                                <div class="form-group">

[textarea textarea-325 class:form-control placeholder "Message"]

</div>

                                               </div>

                                            

                                             <div class="col-lg-12">

                                                     <div class="form-button">

[submit id:submit class:submit "submit"]

</div>

                                             </div>

                                            </div>


You can also apple custom contact form 7.


<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


<?php

//Template Name: Contact

get_header();

?>


<?php


//user posted variables

$name = $_POST['name'];

$email = $_POST['email'];

$message = $_POST['message'];


if($name && $email && $message){


//php mailer variables

$to = get_option('admin_email');

$subject = "Contact Request";

$headers = 'From: '. $email . "\r\n" .

    'Reply-To: ' . $email . "\r\n";


//Here put your Validation and send mail

$sent = wp_mail($to, $subject, strip_tags($message), $headers);

    

if($sent) {

  //message sent!

  echo '<script>

  Swal.fire({

  title: "Thanks For Contacting Us!",

  text: "Your request has been submitted!",

  icon: "success"

});

</script>';       

}

else  {

  //message wasn't sent    

  echo '<script>

  Swal.fire({

  title: "Error Occured!",

  text: "Your request has not been submitted!",

  icon: "error"

});

</script>';     

}

}else{


}


?>




In the template page we should apply it like this…

<div class="col-lg-8">

                                   <div class="contact-form">

                                   <?php echo do_shortcode('[contact-form-7 id="0e559dd" title="dummy form"]') ?>

                                   </div>

                               </div>


Topic: support file meme type(ex: .svg)

// enable support for .cvg image files

function cc_mime_types($mimes) {

    $mimes['svg'] = 'image/svg+xml';

    return $mimes;

  }

add_filter('upload_mimes', 'cc_mime_types');



Topic: Read more and less concept

If you want to display more and less code in your ACF description.


<?php

get_header();

?>


<!-- service detail -->

<main>

    <section class="fmodel sec_pad">

      <div class="col-lg-6">

                    <div class="mid-text" id="description_text">

                        <p class="content-short"> 

                        <?php echo substr(get_field('service_details_description'),0,500); ?>

                        ...

    </p>

    <p class="content-full" style="display: none;"> 

    <?php echo get_field('service_details_description'); ?>

    </p>

    <a href="#" class="btn-underline mt-2 read-more-link">Read More</a>


                    </div>

                </div>

    </section>


</main>



<script>

    document.addEventListener("DOMContentLoaded", function() {

        const readMoreLinks = document.querySelectorAll(".read-more-link");

        

        readMoreLinks.forEach(link => {

            link.addEventListener("click", function(event) {

                event.preventDefault();

                const contentShort = this.parentElement.querySelector(".content-short");

                const contentFull = this.parentElement.querySelector(".content-full");

                

                if (contentShort.style.display === "none") {

                    // Content is expanded, so show short content and update link text

                    contentShort.style.display = "block";

                    contentFull.style.display = "none";

                    this.textContent = "Read More";

                } else {

                    // Content is collapsed, so show full content and update link text

                    contentShort.style.display = "none";

                    contentFull.style.display = "block";

                    this.textContent = "Read Less";

                }

            });

        });

    });

</script>



<?php

get_footer();

?>



Topic: load more

First you need to set the template page along with ‘functions.php’. The main logic will when we click on “load more” button it will show up posts and after the last post list if there is no post, then this button will not exist.


Note: This variable keeps track of the current page of posts being displayed. When the "Load More" button is clicked, it increments to load the next page of posts. This variable defines the number of posts to load per page. It helps in controlling how many posts are fetched and displayed each time the "Load More" button is clicked.


functions.php

// load more

function load_more_posts() {

  $page = $_POST['page'];

  $posts_per_page = $_POST['posts_per_page'];


  $args = array(

      'posts_per_page' => $posts_per_page,

      'paged' => $page,

      'post_type' => 'post'

  );


  $posts = new WP_Query($args);


  if ($posts->have_posts()) {

      while ($posts->have_posts()) {

          $posts->the_post();

          // Your post template here

          ?>

          <div class="col-lg-4 col-sm-6">

              <div class="single-blog-grid">

                  <a href="<?php the_permalink(); ?>">

                      <figure>

                          <?php the_post_thumbnail('medium'); ?>

                      </figure>

                      <figcaption class="text-white">

                          <h3><?php echo get_the_title(); ?></h3>

                          <p class="white-dash"><?php echo get_the_date(); ?></p>

                      </figcaption>

                  </a>

              </div>

          </div>

          <?php

      }

      wp_reset_postdata();

  } else {

      // If no more posts, return empty string

      echo '';

  }


  die();

}

add_action('wp_ajax_load_more_posts', 'load_more_posts');

add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');


In the above code you see the HTML code portion which will render a particular blog against load more.


Ex: blogs.php

<section class="explre_services sec_pad bg-gray">

  

    <div class="container" id="blog-container">

        <div class="row justify-content-center" id="post-container">

            <!-- Posts will be loaded here -->

        </div>

        <div class="text-center mt-4">

            <button class="btn" id="load-more">Load More</button>

        </div>

    </div>


</section>



<script>

    let currentPage = 1;

    const postsPerPage = 2;


    function loadPosts(page) {

        $.ajax({

            type: 'POST',

            url: '<?php echo admin_url('admin-ajax.php'); ?>',

            dataType: 'html',

            data: {

                action: 'load_more_posts',

                page: page,

                posts_per_page: postsPerPage,

            },

            success: function (response) {

                $('#post-container').append(response);

                if (response.trim() === '') {

                    $('#load-more').hide();

                }

            }

        });

    }


    $(document).ready(function () {

        loadPosts(currentPage);


        $('#load-more').on('click', function () {

            currentPage++;

            loadPosts(currentPage);

        });

    });

</script>


Note: if you want to apply for custom post type, then:


functions.php

// load more - services

function load_more_services()

{

    $page = $_POST['page'];

    $posts_per_page = $_POST['posts_per_page'];


    $args = array(

        'posts_per_page' => $posts_per_page,

        'paged' => $page,

        'post_type' => 'services'

    );


    $posts = new WP_Query($args);


    if ($posts->have_posts()) {

        while ($posts->have_posts()) {

            $posts->the_post();

            // Your post template here

            ?>

            <div class="col-lg-4 col-sm-6">

                <div class="single-blog-grid">

                    <a href="<?php the_permalink(); ?>">

                        <figure>

                            <?php the_post_thumbnail('medium'); ?>

                        </figure>

                        <figcaption class="text-white">

                            <h3><?php echo get_the_title(); ?></h3>

                            <p class="white-dash"><?php echo get_the_date(); ?></p>

                        </figcaption>

                    </a>

                </div>

            </div>

            <?php

        }

        wp_reset_postdata();

    } else {

        // If no more posts, return empty string

        echo '';

    }


    die();

}

add_action('wp_ajax_load_more_services', 'load_more_services');

add_action('wp_ajax_nopriv_load_more_services', 'load_more_services');



Service.php - custom template

<main>

 

    <section class="explre_services sec_pad bg-gray position-relative">

       

        <div class="container" id="service-container">

            <div class="row" id="post-container">


                <!--  services lists -->


            </div>

            <div class="text-center mt-4">

                <a href="#" class="btn" id="load-more">Load More</a>

            </div>

        </div>

    </section>


</main>



<script>

    let currentPage = 1;

    const postsPerPage = 2;


    function loadPosts(page) {

        $.ajax({

            type: 'POST',

            url: '<?php echo admin_url('admin-ajax.php'); ?>',

            dataType: 'html',

            data: {

                action: 'load_more_services',

                page: page,

                posts_per_page: postsPerPage,

            },

            success: function (response) {

                $('#post-container').append(response);

                if (response.trim() === '') {

                    $('#load-more').hide();

                }

            }

        });

    }


    $(document).ready(function () {

        loadPosts(currentPage);


        $('#load-more').on('click', function () {

            currentPage++;

            loadPosts(currentPage);

        });

    });

</script>



Topic: newsletter form using mailchimp

When we working on wordpress, sometime we need to work with newsletter subscription form. That time we should work with maichip which will automate our newsletter subscription form process. First create your mailchimp account with your email. Now go to, API section: https://us18.admin.mailchimp.com/account/api/


Now, install WP4MC plugin from wordpress admin. 


Now modify the form code and then paste the generated short code into template page of wordpress. 



Topic: search post

We can make searches in the post. Let’s see how to achieve this … 


Ex: blog.php/template-filename.php

<form role="search" method="get" action="<?php echo esc_url(home_url('/')); ?>">

                            <div class="form-group">

                                <div class="input-group mb-3">

                                    <input  value="<?php echo get_search_query(); ?>" name="s" class="form-control" placeholder="Search Keyword">

                                    <div class="input-group-append">

                                        <button class="btn" type="submit"><i class="ti-search"></i></button>

                                    </div>

                                </div>

                            </div>

                            <button class="button rounded-0 primary-bg text-white w-100" type="submit">Search</button>

                        </form>


Now , you also need to make a “search.php” file.

search.php

<h2>Search Results for "<?php echo get_search_query(); ?>"</h2>


                <br>


                    <?php if ( have_posts() ) : ?>

                        <?php while ( have_posts() ) : the_post(); ?>



                    <?php 

                    $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium');

                    $day = get_the_time(' j ');

                            $month = get_the_time(' F ');

                            ?>

                            <article class="blog_item">

                                <div class="blog_item_img">

                                    <img class="card-img rounded-0" src="<?php echo $thumbnail[0]; ?>" alt="">

                                    <a href="#" class="blog_item_date">

                                        <h3> <?php echo $day; ?> </h3>

                                        <p><?php echo $month; ?></p>

                                    </a>

                                </div>


                                <div class="blog_details">

                                    <a class="d-inline-block" href="<?php echo the_permalink(); ?>">

                                        <h2> <?php echo get_the_title(); ?> </h2>

                                    </a>

                                    <p> <?php echo get_the_excerpt(); 

                                    //echo substr(get_the_content(),0,300)." ... "; ?> 

                                    </p>

                                    <ul class="blog-info-link">

                                        <li><a href="#"><i class="far fa-user"></i> 

                                        <?php

                                        // passing post ID to post categories

                                        $categories = wp_get_post_categories($post_id = get_the_ID()); 

                                        foreach($categories as $category){

                                            $cat = get_category($category);

                                            echo $cat->name.",";

                                        }

                                        ?>

                                    </a></li>

                                        <li><a href="#"><i class="far fa-comments"></i> <?php echo  get_comments_number(); ?> Comments</a></li>

                                    </ul>

                                </div>

                            </article>


                            <?php endwhile; ?>

                    <?php else : ?>

                        <p><?php esc_html_e( 'Sorry, no posts matched your search. Please try again with different keywords.', 'textdomain' ); ?></p>

                    <?php endif; ?>


—----------------------------------------------------------------------------------------------------------------------


We can make a custom form field type. For installing this go to, themes/ folder of your custom theme and paste the command: 

composer require htmlburger/carbon-fields


In your functions.php

use Carbon_Fields\Container;

use Carbon_Fields\Field;


add_action('carbon_fields_register_fields', 'crb_attach_theme_options');

function crb_attach_theme_options()

{

    Container::make('theme_options', __('Theme Options'))

        

         ->add_fields(

           array(

                Field::make('rich_text', 'crb_footer_copyright', 'Copyright'),

           )

        );

}


After that you will get an option as “Theme Options” inside wp-admin and inside there your will find a rich text box.



Let’s see how to make some tabs inside “Theme Options”.

use Carbon_Fields\Container;

use Carbon_Fields\Field;


add_action('carbon_fields_register_fields', 'crb_attach_theme_options');

function crb_attach_theme_options()

{

    Container::make('theme_options', __('Theme Options'))

        ->add_tab(

            'Footer',

            array(

                Field::make('rich_text', 'crb_footer_copyright', 'Copyright'),

            )

        )

        ->add_tab(

            'Social',

            array(

                Field::make('text', 'crb_social_url_facebook', 'Facebook URL')

                    ->set_help_text('Enter your Facebook page url'),

                Field::make('text', 'crb_social_url_twitter', 'Twitter URL')

                    ->set_help_text('Enter your Twitter profile url'),

            )

        );


}


Let’s see some react of these… 



Note: you can wrap up carbon fields with some specific pages.


functions.php

add_action('carbon_fields_register_fields', 'crb_attach_post_meta');

function crb_attach_post_meta()

{

    // mentioning the post id(page) -- ex: departments

    $post_id = '355';


    Container::make('post_meta', __('Product Custom Fields', 'cpg'))

        ->where('post_type', '=', 'page')

        ->where('post_id', '=', $post_id)

        ->add_tab(

            'Banner Area',

            array(

                Field::make('text', 'cpg_product_heading', 'Banner Heading'),

                Field::make('text', 'cpg_product_short_text', 'Banner Short Text'),

                Field::make('text', 'cpg_product_url', 'Product Page URL')->set_attribute('type', 'url'),

            )

        )

        ->add_tab('Products',array(

                Field::make('complex', 'crb_slides', 'Slides')

                    ->set_layout('tabbed-horizontal')

                    ->add_fields(

                        array(

                            Field::make('image', 'cpg_product_thumbnail', 'Product Thumbnail'),

                            Field::make('text', 'cpg_product_full_name', 'Product Full Name'),

                            Field::make('text', 'cpg_product_price', 'Product Price'),

                        )),

            )

        );

}




You can associate some common carbon fields with all posts or even specific post too.

Container::make('post_meta', __('Post Custom Fields', 'crb'))

        ->where('post_type', '=', 'post')



Note: sometimes we need to add some custom classes to active fields/pages where we stay … how to load that class for that..

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);


function special_nav_class ($classes, $item) {

  if (in_array('current-menu-item', $classes) ){

    $classes[] = 'active ';

  }

  return $classes;

}  



Topic: Option Panel enable

We can enable the option panel in wp-admin. After that you will get a “Theme Options” inside the admin panel.



function.php

// option panel enable

if( function_exists('acf_add_options_page') ) {

// Add the Theme General Settings page

acf_add_options_page(array(

     'page_title' => 'Theme General Settings',

     'menu_title' => 'Theme Settings',

     'menu_slug' => 'theme-general-settings',

     'capability' => 'manage_options', // Change capability to manage_options

     'redirect'  => false

));


// Add the Theme Header Settings subpage

acf_add_options_sub_page(array(

     'page_title' => 'Theme Header Settings',

     'menu_title' => 'Header',

     'parent_slug'   => 'theme-general-settings',

     'capability' => 'manage_options' // Make sure it has the same capability as the parent

));


// Add the Theme Footer Settings subpage

acf_add_options_sub_page(array(

     'page_title' => 'Theme Footer Settings',

     'menu_title' => 'Footer',

     'parent_slug'   => 'theme-general-settings',

     'capability' => 'manage_options' // Make sure it has the same capability as the parent

));


}


How to get the option value … in themes

// get option page value

// syntax: <p><?php the_field('field_name', 'option'); ?></p>

<?php echo get_field('copyright_text', 'option'); ?>




Popular posts from this blog

gemini cheat sheet - py

custom user model in django