How to Create the Default WordPress .htaccess File

The .htaccess is a distributed configuration file and is how Apache handles configuration changes on a per-directory basis.

WordPress uses the .htaccess file to manipulate how Apache serves files from its root directory and subdirectories thereof. Most notably, WordPress modifies this file to be able to handle pretty permalinks.

This page may be used to restore a corrupted .htaccess file or a misbehaving plugin.

This is the Default WordPress .htaccess configuration


    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    # END WordPress

This is the WordPress .htaccess configuration for a website that has a sub-directory


    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /foldername/
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /foldername/index.php [L]
    </IfModule>
    # END WordPress

As a personal preference, we prefer to have sub-domains for our client’s websites, in all honestly, it makes it so much easier in terms of setting up and not breaking the structure. Should you want to host your websites on sub-directories though, ensure the path is correct and that you update the .htaccess file to accommodate the correct path.

We hope this has helped, thanks for reading!

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to Prevent Multi-Submit on Contact Form 7

Recently, we came across an issue where we were using the Mail (2) setting to send an automated email to a user who submits the form with an attachment. The issue was that this attachment was a 2MB file, so before you see the success message, you have to wait for the attachment to be sent which can take a bit of time. Because of this, users end up submitting the forms various times causing multiple submits and emails send to both parties (Especially when using a 3rd party SMTP host like SendGrid or MailGun).

Here is the method we used to prevent this sort of action which can simply be added to your functions.php file to be called on each page.


<?php
	// Prevent Multi Submit on all WPCF7 forms
	add_action( 'wp_footer', 'prevent_cf7_multiple_emails' );

	function prevent_cf7_multiple_emails() {
	?>

	<script type="text/javascript">
	var disableSubmit = false;
	jQuery('input.wpcf7-submit[type="submit"]').click(function() {
	    jQuery(':input[type="submit"]').attr('value',"Sending...");
	    if (disableSubmit == true) {
	        return false;
	    }
	    disableSubmit = true;
	    return true;
	})
	  
	var wpcf7Elm = document.querySelector( '.wpcf7' );
	wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
	    jQuery(':input[type="submit"]').attr('value',"Sent");
	    disableSubmit = false;
	}, false );

	wpcf7Elm.addEventListener( 'wpcf7invalid', function( event ) {
	    jQuery('#wpcf7-f549-o1 :input[type="submit"]').attr('value',"Submit")
	    disableSubmit = false;
	}, false );
	</script>
	<?php
} ?>

What the above will do is change the text of the forms submit button to ‘Sending…’ and disable any further clicks until the message is delivered. Once the message is delivered, the submit button will change to ‘Sent’.

In addition to this, if there are any errors in the form, we can use the wpcf7invalid DOM Event which we can use to change the value of the submit button back to the original value; in our case, we changed it back to ‘Submit’.

In our case, we had pages with multiple forms and only needed this to be added to one of the forms on the website. To do this, you can view the page source and get the ID attribute for the form (e.g. #wpcf7-f4-o1), and simply add this before each of the selectors.

There are other ways of doing this such as using a preloader on submit but our particular client was pretty happy with the solution we provided him with.

Feel free to leave a comment below if this has helped or if you have another preferred method of performing such a task.

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to Display WooCommerce Product Reviews on Custom Page with a Shortcode

By default with WooCommerce, product reviews display by default in the ‘Reviews’ tab in a single product page. What we are going to show you today is how you can display them on any page of your website using a shortcode. This can be especially useful if you are using custom sales pages and need to show reviews on specific pages about a certain product.

So let’s dig into this…

Creating the WooCommerce Product Reviews Shortcode

Firstly, we need to add some code to our functions.php file:


/**
 * WooCommerce Product Reviews Shortcode
 */
 
add_shortcode( 'product_reviews', 'silva_product_reviews_shortcode' );
 
function silva_product_reviews_shortcode( $atts ) {
    
   if ( empty( $atts ) ) return '';
 
   if ( ! isset( $atts['id'] ) ) return '';
       
   $comments = get_comments( 'post_id=' . $atts['id'] );
    
   if ( ! $comments ) return '';
    
   $html .= '<div class="woocommerce-tabs"><div id="reviews"><ol class="commentlist">';
    
   foreach ( $comments as $comment ) {   
      $rating = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) );
      $html .= '<li class="review">';
      $html .= get_avatar( $comment, '60' );
      $html .= '<div class="comment-text">';
      if ( $rating ) $html .= wc_get_rating_html( $rating );
      $html .= '<p class="meta"><strong class="woocommerce-review__author">';
      $html .= get_comment_author( $comment );
      $html .= '</strong></p>';
      $html .= '<div class="description">';
      $html .= $comment->comment_content;
      $html .= '</div></div>';
      $html .= '</li>';
   }
    
   $html .= '</ol></div></div>';
    
   return $html;
}

Adding the Shortcode

Once you’ve added the code to your functions.php file, we can now use the following shortcode on any page you like; [product_reviews id="ID"].

Simply replace the text ID with the product for which you want to output your customer reviews and that is simply all there is to it!

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to create a WordPress Widget

A WordPress widget makes it easy for users to simply drag and drop elements into their site. There are many WordPress themes and plugins that use widgets to allow users to create their own layouts. In this article, we will show you how to create your own custom WordPress widget from scratch.

What is a WordPress Widget?

A WordPress widget was originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. The great thing about widgets is that you can drag and drop them into your sidebars or any widget-ready areas of your website. This allows great flexibility to plugin and theme developers. They can add functionality into their products and let users decide when and where to use that functionality without messing with code. Similarly, as a user you can also create your own widgets in a site-specific plugin so that you can drag and drop them into any theme you are using.

Creating your first Widget in WordPress

In this demonstration, we are going to add the widget through our functions.php file. We are going to create a simple widget that displays the current date and time. Take a look at this code and then paste it in your site-specific plugin to see it in action:-


// Creating the widget 
class wpb_widget extends WP_Widget {

function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget', 

// Widget name will appear in UI
__('Silva Time Widget', 'wpb_widget_domain'), 

// Widget description
array( 'description' => __( 'Sample widget based on Silva Web Designs Tutorial', 'wpb_widget_domain' ), ) 
);
}

// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];

// This is where you run the code and display the output
$widget_content  = "Today is " . date("d/m/Y");

echo __( $widget_content, 'wpb_widget_domain' );
echo $args['after_widget'];
}
		
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( '', 'wpb_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php 
}
	
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class wpb_widget ends here

// Register and load the widget
function wpb_load_widget() {
	register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );

Now go to Appearance --> , drag and drop Silva Time Widget in your sidebar to see this custom widget in action.

Simple wasn't it? First, we created a custom widget. Then we defined what that widget does and how to display the widget back-end. Then we defined how to handle changes made to the widget. Lastly, we registered and loaded the widget.

Now there are a few things that you might want to ask. For example, what wpb_text_domain does? WordPress uses gettext to handle translation and localization. This wpb_text_domain and __e tells gettext to make a string available for translation.

We hope this tutorial helped you learn how to create a custom WordPress widget. Let us know what widgets you are creating, by leaving a comment below.

If you have moved the widget into your sidebar, you can go to one of your WordPress pages to see the output code which will display the following:-

Today is DD/MM/YYYY.

I hope this helps!

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to use jQuery in WordPress

Have you ever tried using jQuery in WordPress and couldn’t find out why it wasn’t working?

The reason behind this is simple and is probably not working because your code looks something like this example below:-


$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
});

So why does this not work?

The reason is that in the console area when you view the code inspector, no doubt you will have an error that says something along the lines of jQuery cannot be defined. There are different ways to fix this, the ‘best’ way of fixing this is by editing the ‘enqueue’ setting which is usually within your functions.php file:-


wp_enqueue_script("jquery");

The code above is typically the default setting for WordPress Themes. This means that the usual ‘$’ shortcut for jQuery doesn’t work.

Most of the developers of plugins and theme developers are already aware of this, and they use ‘jQuery’ as opposed to ‘$’ to be safe and to ensure the plugin will be compatible.


/**** Typical jQuery ***/
$("#foo").doSomething();

/*** "Safe" method of jQuery in WordPress ***/
jQuery("#foo").doSomething();

The most frustrating thing about using ‘jQuery’ as opposed to ‘$’ everywhere within your WordPress files is that it doesn’t look as clean which makes it harder to read and that it bloats the size of your website.

If the script is being loaded in the footer (which you should be doing in the vast majority of cases) you can wrap the code in an anonymous function where you pass in jQuery to be mapped to $ as follows:-


(function($) {
	
	// $ Works! You can test it with next line if you like
	// console.log($);
	
})( jQuery );

If you really need to load the scripts in the header, you will probably need to use a document ready function anyway, so you can just pass in $ as follows:-


jQuery(document).ready(function( $ ) {
	
	// $ Works! You can test it with next line if you like
	// console.log($);
	
});

I hope this article has helped you solve the problem. Feel free to comment below if this has helped you in any way!

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to Dynamically Add a WordPress Post Title in Contact Form 7

The Contact Form 7 WordPress plugin is a very powerful plugin that is very typically used on a lot of WordPress websites that requires forms. There are times we run into situations where we need to dynamically add a WordPress post title, URL or fields in either the subject line or email body generated by the form. Luckily, this situation is very easy to handle with the help of an extension plugin. In this tutorial, we will teach you how to dynamically add a WordPress post title in the Contact Form 7 plugin.

Step 1: Install the Contact Form 7 Dynamic Text Extension Plugin

First things first, we need to download and install the ‘Contact Form 7 Dynamic Text Extension Plugin’ from the WordPress plugin directory. This plugin will allow the ability to add dynamic content capabilities to the ‘Contact Form 7 Plugin’.

Please Note:

  • – Make sure that you also have the ‘Contact Form 7 Plugin’ installed.
  • – This is a very powerful plugin and dynamically adding the WordPress post title is just one of its many capabilities.

Step 2: Generate the Hidden Dynamic Content Tag in Contact Form 7

Now we will generate the hidden dynamic content tag that will be used to dynamically add the WordPress post title in ‘Contact Form 7’.

While in the WordPress Dashboard, go to the ‘Contact Form 7’ settings page and make sure you are viewing the ‘Form’ tab. Copy and paste the form-tag code below then add it inside the form code block:-


[dynamichidden page-title "CF7_get_post_var key='title'"]

The above code will add a hidden text input to the form which will pre-populate the page title. This is good to use when you are using the same contact form on multiple pages so you know where the user has submitted the form from.

Alternatively, you can display the page URL or slug using one of the below shortcodes instead:-


[dynamichidden page-url "CF7_bloginfo show='url'"]
[dynamichidden page-slug "CF7_bloginfo show='url'"]

Step 3: Displaying the Hidden Dynamic Content Tag Variable in Contact Form 7

Finally, we will display the hidden dynamic content tag variable in ‘Contact Form 7’ form.

While still on the ‘Contact Form 7’ settings page, click on the ‘Email’ tab. You can now use the variable code tag below to display the WordPress post title in either the ‘Subject’ or ‘Message Body’ of the ‘Contact Form 7’ form.


[page-title]

If you are using the URL or Slug fields in this example, you would use the below code tag:-


[page-url]
[page-slug]

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible. We hope this helps.

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

ACF Repeater Load More using AJAX

Have you ever wanted to show a limited amount of items when using an ACF repeater? Maybe you are using this to display images and to save on load time you only want to show a selective amount instead of loading them all. At the end of the day, having to load fewer images is going to speed up your site right?

In this example, we will show you the basics of adding load more functionality for an ACF repeater field. We are going to display a repeater called gallery and load only 9 items if there are more than 9 items we will display a ‘Load more’ button to programmatically load the rest.

So first of all our markup will look as follows:-


<div id="photo-gallery">
	<div class="row">
		<?php
		if( have_rows('media') ): 
			$total = count(get_field('media'));
			$count = 0;
			$number = 8;					
			while ( have_rows('media') ) : the_row(); ?>						
					<div class="col-md-4 col-sm-6">
						<a class="mag-pop" data-img="<?php the_sub_field('image'); ?>" href="<?php the_sub_field('image'); ?>"><img class="img-gallery" alt="BeWILDerwood Gallery" src="<?php the_sub_field('image'); ?>" /></a>
					</div>
				<?php
				if ($count == $number) {
					// we've shown the number, break out of loop
					break;
				} ?>					
			<?php $count++; endwhile;
		else : endif;
		?>
	</div>
	<a id="gallery-load-more" href="javascript: my_repeater_show_more();" <?php if ($total < $count) { ?> style="display: none;"<?php } ?>><h2 id="title-bg"><span>Load more</span></h2></a>
</div>

As you can see, $number defined the number of repeater items we want to initially display. We use the break; clause to prevent further images from loading.

Now moving on to the JavaScript:-


<script type="text/javascript">
	var my_repeater_field_post_id = <?php echo $post->ID; ?>;
	var my_repeater_field_offset = <?php echo $number + 1; ?>;
	var my_repeater_field_nonce = '<?php echo wp_create_nonce('my_repeater_field_nonce'); ?>';
	var my_repeater_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
	var my_repeater_more = true;
	
	function my_repeater_show_more() {
		
		// make ajax request
		jQuery.post(
			my_repeater_ajax_url, {
				// this is the AJAX action we set up in PHP
				'action': 'my_repeater_show_more',
				'post_id': my_repeater_field_post_id,
				'offset': my_repeater_field_offset,
				'nonce': my_repeater_field_nonce
			},
			function (json) {
				// add content to container
				// this ID must match the containter 
				// you want to append content to
				jQuery('#photo-gallery .row').append(json['content']);
				// update offset
				my_repeater_field_offset = json['offset'];
				// see if there is more, if not then hide the more link
				if (!json['more']) {
					// this ID must match the id of the show more link
					jQuery('#gallery-load-more').css('display', 'none');
				}
			},
			'json'
		);
	}
	
</script>

We’ve added comments within the code so you can see what is happening through the process. Now we need to add the code to the functions.php file to load the additional items.


/**
 * ACF Load More Repeater
*/

// add action for logged in users
add_action('wp_ajax_my_repeater_show_more', 'my_repeater_show_more');
// add action for non logged in users
add_action('wp_ajax_nopriv_my_repeater_show_more', 'my_repeater_show_more');

function my_repeater_show_more() {
	// validate the nonce
	if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'my_repeater_field_nonce')) {
		exit;
	}
	// make sure we have the other values
	if (!isset($_POST['post_id']) || !isset($_POST['offset'])) {
		return;
	}
	$show = 9; // how many more to show
	$start = $_POST['offset'];
	$end = $start+$show;
	$post_id = $_POST['post_id'];
	// use an object buffer to capture the html output
	// alternately you could create a varaible like $html
	// and add the content to this string, but I find
	// object buffers make the code easier to work with
	ob_start();
	if (have_rows('media', $post_id)) {
		$total = count(get_field('media', $post_id));
		$count = 0;
		while (have_rows('media', $post_id)) {
			the_row();
			if ($count < $start) {
				// we have not gotten to where
				// we need to start showing
				// increment count and continue
				$count++;
				continue;
			}
			?>
			<div class="col-md-4 col-sm-6">
				<a class="mag-pop" data-img="<?php the_sub_field('image'); ?>" href="<?php the_sub_field('image'); ?>"><img class="img-gallery" alt="BeWILDerwood Gallery" src="<?php the_sub_field('image'); ?>" /></a>
			</div>
			<?php 
			$count++;
			if ($count == $end) {
				// we've shown the number, break out of loop
				break;
			}
		} // end while have rows
	} // end if have rows
	$content = ob_get_clean();
	// check to see if we've shown the last item
	$more = false;
	if ($total > $count) {
		$more = true;
	}
	// output our 3 values as a json encoded array
	echo json_encode(array('content' => $content, 'more' => $more, 'offset' => $end));
	exit;
} // end function my_repeater_show_more

As you can see above, we are going to load an additional 9 images (or repeater values) on click of the load more button. Once all loaded items have appeared, we are hiding the load more button so that is no longer visible.

And that’s pretty much it! If this has helped you, feel free to drop a comment. If you need any help with this, feel free to get in touch and we’ll be happy to assist you! 🙂

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to Change the Placeholder text for the WordPress Search Form

Today we will learn how to change the placeholder text for WordPress search forms.

To display a WordPress search form you can use the following PHP code:-


<?php get_search_form(); ?>

Now, we just need to add the below code to your functions.php /** * Search Form */ function wp_search_form( $form ) { $form = '<section class="search search-form"><form role="search" method="get" action="' . home_url( '/' ) . '" > <label class="screen-reader-text" for="s">' . __('', 'domain') . '</label> <input type="search" class="search-field" value="' . get_search_query() . '" name="s" id="s" placeholder="" /> <input type="submit" id="searchsubmit" class="search-submit" value="'. esc_attr__('Go', 'domain') .'" /> </form></section>'; return $form; } add_filter( 'get_search_form', 'wp_search_form' );

We hope this article has helped you to be able to change the placeholder text for the WordPress search box.

Are you wanting to customise the default WordPress Search?

You may also be wondering how you can customise the default search to only display certain things. For example, you may not want to search for posts, but only display pages or certain CPT (Custom Post Types). This can also be done bespoke, but we tend to find the Relevanssi – A Better Search plugin to do the job perfectly well, and safe quite a bit of time. Relevanssi replaces the standard WordPress search with a better search engine, with lots of features and configurable options. You'll get better results, better presentation of results and your users will thank you.

If you need assistance with setting this up, feel free to get in touch, we look forward to hearing from you.

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share