How to show posts under custom post type taxonomy?

Custom post types make things easier when you need something special done other than generic post or page. Here you can learn more about custom post types.

Long story short, suppose you have a real estate property listing website. You need to show properties based on property type in a page. Means you want to show Commercial and residential properties in a page. Then, you need to create a custom loop that will show properties under a custom post types taxonomy.

To do that, you need to define an argument first.

$args = array( 'post_type' => 'property', 
		'tax_query' => array(
			array(
				'taxonomy' => 'property-type',
				'field' => 'slug',
				'terms' => 'commercial'
			     )
			), 			
		'posts_per_page' => 10 
	    );

post_type: This is the custom post types name. The name exactly you have registered. In the example, I’ve used  property.

tax_query: tax_query takes an array of tax query arguments arrays. As property-type is a taxonomy we want to show, that’s why we need define its filed and terms name. “field” is to select taxonomy term by. Possible values are ‘term_id’, ‘name’, ‘slug’ or ‘term_taxonomy_id’. Default value is ‘term_id’. And the “terms” is axonomy term(s).

In the example, I have used slug and the taxonomy terms commercial as I want to show commercial properties in a page.

posts_per_page:  This is to for how many post you want to show in a page. The value will be in “int”. The value “-1” means unlimited posts.

Now, we need to create the default loop that will show the posts/properties anywhere you want to show. It can be custom page template or post or page. Here you go…


$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
/* Display Property for Home Page */
/* get_template_part('template-parts/property-for-home'); */
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile;

Now add these spinnets together in a single.php , custom-single.php or custom page template. This is it.

Here is the look:

$args = array( 'post_type' => 'property', 
		'tax_query' => array(
			array(
				'taxonomy' => 'property-type',
				'field' => 'slug',
				'terms' => 'commercial'
			     )
			), 			
		'posts_per_page' => 10 
	    );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
/* Display Property for Home Page */
/* get_template_part('template-parts/property-for-home'); */
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile;

Here is the result.

add codes in child theme header

How to Add Codes in Child Theme Header

We are generally comfortable to add things as our wish in the header, even in the footer. Because the most themes are the parent theme. Premium themes come with extra options where you can add Google analytics codes, Meta tags, custom texts, phone number, even a search box etc. So in this post, you will learn about how to add codes in child themes header.

How to add codes in Child theme’s header.php

You may be wondering about copying the parent theme’s header.php and paste in the child theme. Yeah, it works. But when you can edit child theme’s functions.php, why do you need an extra header.php file? Well, let’s see how we can make it work using some codes.

Open your child theme’s functions.php and paste these codes.

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
    
    ?>
    //Add here HTML or JS codes
    <?php 
}

For an instance, you want to add Google Analytics codes within tags. Just add these codes in child’s functions.php

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
    
    ?>
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<?php 
}

You can also add shortcode too. Just like these

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
    
   echo do_shortcode("[shortcode]");
}

You can add some HTML codes too.

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
   ?> 
    <h4>It's a H4 title</h4>
    <a href="#"> Test Hyperlink</a>
  <?php
}

add codes in child theme header

If you want to insert a search form, here you go….

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
  <?php get_search_form(); ?>
}

Check out these codes in Git

So, here you have learned how to add custom HTML, JS, PHP codes even some style in child theme’s header very easily. Just make sure you are adding contents in header specific DIV. Otherwise, it will be looking awkward.

create wordpress child theme

How to Create WordPress Child Theme in 5 minutes

WordPress is like a garden if you have HTML CSS PHP JS knowledge, you can extend your site looks and function easily. Also, you can outrun your competitor. In present days, around 40% websites run on WordPress. Amazing Nah?

Generally, WordPress comes with few default themes. You can extend them by creating a child theme, you can make a new theme too. In this tutorial, I will show you how to create a WordPress Child theme in just 5 minutes that export all the functions from the Parent theme.

Create WordPress Child Theme Step by Step

Step 1 (1 minute):

First, create a folder in the same directory of the parent theme. The themes directory can be browsed through FTP or CPanel file manager or XAMP/WAMP/MAMP’s htdocs. You know where your WordPress file located. Rename it, let’s say we are making twenty sixteens’ child theme, “Twenty Sixteen Child”.

Step 2(2 minutes):

Now, copy the parent theme’s stylesheet to the child theme folder. Remove everything except these lines….

/*
Theme Name: Twenty Sixteen
Theme URI: https://wordpress.org/themes/twentysixteen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Sixteen is a modernized take on an ever-popular WordPress layout — the horizontal masthead with an optional right sidebar that works perfectly for blogs and websites. It has custom color options with beautiful default color schemes, a harmonious fluid grid using a mobile-first approach, and impeccable polish in every detail. Twenty Sixteen will make your WordPress look beautiful everywhere.
Version: 1.3
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: one-column, two-columns, right-sidebar, accessibility-ready, custom-background, custom-colors, custom-header, custom-menu, editor-style, featured-images, flexible-header, microformats, post-formats, rtl-language-support, sticky-post, threaded-comments, translation-ready, blog
Text Domain: twentysixteen

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you’ve learned with others.
*/

Now, replace those line to these…

/*
Theme Name: Twenty Sixteen Child
Theme URI: https://wordpress.org/themes/twentysixteen/
Author: Your Name
Author URI: https://yoursite.com/
Template: twentysixteen
Description: Twenty Sixteen is a modernized take on an ever-popular WordPress layout — the horizontal masthead with an optional right sidebar that works perfectly for blogs and websites. It has custom color options with beautiful default color schemes, a harmonious fluid grid using a mobile-first approach, and impeccable polish in every detail. Twenty Sixteen will make your WordPress look beautiful everywhere.
Version: 1.3
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: one-column, two-columns, right-sidebar, accessibility-ready, custom-background, custom-colors, custom-header, custom-menu, editor-style, featured-images, flexible-header, microformats, post-formats, rtl-language-support, sticky-post, threaded-comments, translation-ready, blog
Text Domain: twentysixteen-child

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you’ve learned with others.
*/

Did you notice the difference? See, you need to add an extra line Template: twentysixteen . Without this line, your themes will look broken. Be aware that it is case-sensitive. So put the right name. This part in very important. Also, edit the theme name, author name, author website, and theme text-domain as you wish. If you wish you can remove the extra texting. No matter.

To show themes thumbnail in themes page, copy an image to the child theme folder and rename it “screenshot”.

Step 3(2 minutes):

Now, activate the child theme and visit your site. You will see site looks awkward.
WordPress CSS missing

Don’t worry. It means your stylesheet is empty. So you need to import parent theme CSS to the child theme.

Add this line in the style.css in the child theme.

@import url(“../twentysixteen/style.css”);

Now, refresh your site and it looks fine. 🙂 You are apparently done. Time to start customizing its CSS as you wish.

For Developers

For further development of the child themes, you need to add a functions.php file. Where you can add PHP codes to add extra functionality. For an instance, if you wish to add something in header.php. It’s better writing few codes in functions.php than creating a header.php file in the child theme.

add_action('wp_head', 'mwp_header');
function mwp_header(){
    ?>
    Add your codes here. example: Meta tags, google analytics code, extra text etc.
    <?php 
}

Generally, most of the WordPress themes work this way. The question is why we need to create a child theme in WordPress? Well, Parent themes are updating regularly. Suppose if you made some CSS or PHP changes in the parent theme. When you update the parent theme to its latest version, you lose everything you made changes earlier. So, it’s better to make a child theme and make changes as your wish there. When your Parent theme updated, just replace the previous version of parent theme with the latest version. You won’t lose anything cause your child theme has already got every function from parent themes automatically.

ajaxify woocommerce cart

How to Ajaxify Woocommerce Cart for Automatic Cart Update

Generally, when you create Woocommerce supported themes from the scratch, you need to show a cart in the top header. Mostly a tiny piece of code is used to show the cart. But not sufficient when you want to update cart item and price automatically when a product added or removed. That is why you need to Ajaxify cart.

How to Ajaxify Woocommerce Cart

Generally, this code will show a cart in themes. Although it doesn’t update automatically cart item and price.

<a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>

Rather, to update price and product automatically, add this code in functions.php, then it will update cart when a product added or removed.

// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php).
// Used in conjunction with https://gist.github.com/DanielSantoro/1d0dc206e242239624eb71b2636ab148
// Compatible with WooCommerce 3.0+. Thanks to Alex for assisting with an update!
 
function woocommerce_header_add_to_cart_fragment( $fragments ) {
	global $woocommerce;

	ob_start();

	?>
	<a class="cart-customlocation" href="<?php echo esc_url(wc_get_cart_url()); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
	<?php
	$fragments['a.cart-customlocation'] = ob_get_clean();
	return $fragments;
}

Code Explanation

First, you need to add a custom function using add_filter to current Woocommerce function “add_to_cart_fragments”.

Second, use ajax so that the script will not send a request to another page. According to PHP manual “The ob_start() function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.”

The $fragments parameter gets the ob_get_clean() to obtain current buffer contents and deletes the output buffer.