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. I hope this helps.

It’s good to share

How To Auto Redirect Users After Logout In WordPress

This is a useful trick if you’re developing a website for client on WordPress and want to manually redirect users after logout of your WordPress website. By default, WordPress will redirect them to the login page of your website, but we can easily change it by adding following snippet to the current theme’s functions.php file:


add_action('wp_logout','auto_redirect_after_logout');
function auto_redirect_after_logout(){
  wp_redirect( home_url() );
  exit();
}

The above code snippet will redirect your users to the homepage of your website. You can also define a custom URL or external URL by adding the following snippet:


add_action('wp_logout','auto_redirect_external_after_logout');
function auto_redirect_external_after_logout(){
  wp_redirect( 'https://silvawebdesigns.com' );
  exit();
}

It’s good to share

Notify a WordPress User when their Role has Been Changed to a Specific Role

Do you want to send an email on user role change in WordPress? Then you have come to the right place.

Let’s say you want to notify a user if their role has been changed from Subscriber to Contributor, we can do this using the below code:-


function user_role_update( $user_id, $new_role ) {
    if ($new_role == 'contributor') {
        $site_url = get_bloginfo('wpurl');
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email;
        $subject = "Role changed: ".$site_url."";
        $message = "Hello " .$user_info->display_name . " your role has changed on ".$site_url.", congratulations you are now an " . $new_role;
        wp_mail($to, $subject, $message);
    }
}
add_action( 'set_user_role', 'user_role_update', 10, 2);

This will also work with newly created roles you have added. I tend to use Advanced Access Manager plugin to add newly created roles as it gives more flexibility in their permissions.

In my case, I wanted to send out an automated email to a WordPress user once their account has been approved. Using the above code I was able to achieve exactly what I wanted.

I hope this helps!

It’s good to share

WooCommerce: Disable Payment Gateway for Specific User Role

You may want to disable payment gateways depending on the user role or user capability. For example, you may want to disable PayPal for ‘user role: subscriber’ or enable a specific gateway for another user role. This can be achieve without a plugin, all you need to do is paste the following code in your functions.php file.


/**
 * Disable Payment Gateway for a Specific User Role | WooCommerce
 */

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_private' );

 function payment_gateway_disable_private( $available_gateways ) {

    $user = wp_get_current_user();

    if ( isset( $available_gateways['cod'] ) && !is_user_logged_in() || isset( $available_gateways['cod'] ) && in_array('subscriber', $user->roles)  ) {
        unset( $available_gateways['cod'] );
    }

   return $available_gateways;

}

So what the above code will do is remove the ‘Cash On Delivery’ option if you are not logged in, or if you are a user with the ‘Subscriber’ role.

How to Find WooCommerce Payment Gateway ID

If you navigate to WooCommerce –> Settings –> Payments tab, if you inspect the element or view source of this page, you will see a list of codes within a table of all the gateways available on your website as shown in the below screenshot:

Is there a Plugin alternative?

If you don’t feel 100% confident with coding there is a plugin available which offers the same capabilities as the non-plugin method.

There is a plugin called WooCommerce Conditional Payment Gateways to be the most complete when you need to enable/disable payment gateways based on certain criteria. You can create unlimited ‘rules’ and use, for example, cart totals, billing country, shipping country, user role and much more to define which payment gateway shows and which not.

It’s good to share

Websites by Silva Web Designs…

As you may already know, we are a team of developers working remotely across the world, working together to deliver projects in a timely manner without compromising quality!

We offer the following packages:-

  • Brand design
  • Responsive design
  • CMS systems
  • E-commerce
  • Email campaigns
  • SEO (Search Engine Optimisation)
  • App development
  • Hosting
  • Social Media Marketing
  • Copywriting / Content Creation

 

And much more, however, our main passion is web design!

So what do you get from a website build by Silva Web Designs?

In a nutshell, you will get a clean, responsive website that is fully optimised for SEO and speed. We can help you grow your business, whether you need assistance with Copywriting, Google Adwords, Social Media Marketing or anything else in the digital world… we have you covered!

We also provide maintenance and love to develop long-term relationships with our clients, our goal is to help you with every step of your journey to make you as successful as you can be.

Between our team, we have decades of agency experience in building websites that convert… Don’t be fooled by crazy agency prices when you can get the same (or a lot better) quality delivered for a massive deduction of the price!

Which frameworks do we use?

We love WordPress but that’s not our limit, we also work with Squarespace, Drupal, Magento, Shopify, OpenCart, PrestaShop and Larvael to name a few. Whatever the project, we can deliver.

So how do you deliver such a great service?

Taking our most recent project; BeauSocial.

The client wanted a single page web site and needed our team to create a bespoke design and bespoke WordPress theme for their new website. They needed a fairly quick turnaround, a few days… not weeks! (or months, god forbid)

And so we got cracking on this for our client immediately and delivered in just a few days 😉

That’s not to say we rushed the job, we just have the experience to deliver quality work 24/7 to keep out clients super satisfied.

95% of the time, we build bespoke websites, why? Because it gives us the ability to build a website without any restrictions, is built with SEO and speed in mind from the get-go and it’s very easy to update any content/images and everything else across the site.

So the result of BeauSocial was as follows; here is the design of the website:-

https://beausocial.com

As you can see, it’s pixel-perfect to function correctly regardless of browser size and device. Responsive websites at it’s best 😉

Okay, so what else? Well, speed is a major important factor with SEO and the results below show that we definitely adhered to our promises:-

We then continued to support our client helping with their social media accounts, Google AdWords campaigns and providing regular maintenance on their website.

Client = Estatic.

Summary

We have helped a lot of clients now achieving their digital goals at a fraction of the price that you would pay a digital agency.

Is there any benefit to using a design agency? The simple answer is no. You will get the same or better quality and a quicker turnaround in most cases and a massively discounted price that you would pay any agency… People always believe that paying more will result in better quality but that’s not the case in web design at all.

If you need a web developer for your next project, whether it’s a complete rebuild, new website, website updates, maintenance or anything else in the digital world, feel free to drop us an email and we would love to work with you; [email protected]

If you have come this far, thanks for reading… look forward to working with you in the future.

∆ The Silva Team ∆

It’s good to share

Load More Posts Ajax Button in WordPress

In today’s post, I will show you how to create a load more button to show additional posts or custom post types using AJAX.

The benefit of this is that it will improve the page load of the page as it will only be displaying a certain amount of posts before having to load any more of the content.

So let’s get started…

So the first thing that you should have is a list of posts to display on the frontend as follows:-


    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

Then you want to add the following code in your functions.php file.


wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file, you need to add the function that will load your posts:-


function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

The final part is the ajax itself. In functions.js or your main JavaScript/jQuery file, you need to input inside the $(document).ready(); environment the following code:-


var ppp = 3; // Post per page
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = ''&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

With the above code, you should now have a load more button at the bottom of your posts where on click it will display further posts. This can also be used with CTP (custom post types).

If you need any help with this, feel free to get in touch in the comment below. This can also be used to load automatically on scroll, again, if you need help with this, just drop me a message and I’ll be more than happy to help you!

It’s good to share

How to Increase the Maximum File Upload Size in WordPress

Do you have a large file that you can’t upload to WordPress due to limitations? Do you want to increase the maximum file upload size in WordPress? Some times low file upload size limit can stop you from uploading files via media uploader, or install plugins and themes. In this article, we will show you how to easily increase the maximum file upload size in WordPress to correct that issue.

How to Check Your Maximum File Upload Size Limit in WordPress?

WordPress will automatically show the maximum file upload size limit when you are uploading images or media. To check this, you can simply go to Media > Add New page and you will see the maximum file upload size limit for your WordPress site.

So how do we fix this?

Method 1

In some cases you can just add the following code in theme’s functions.php file to increase the upload size:


@ini_set( 'upload_max_size' , '64M' );
@ini_set( 'post_max_size', '64M');
@ini_set( 'max_execution_time', '300' );

Method 2

Create or Edit an existing PHP.INI file. For this method you will need to access your WordPress site’s root folder by using FTP or File Manager app in your hosting account’s cPanel/Plesk dashboard.

In most cases, if you are on a shared host, then you will not see a php.ini file in your directory. If you do not see one, then create a file called php.ini and upload it in the root folder. In that file add the following code:-


upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300

This method is reported to work for many users. Remember if 64 doesn’t work, then try 10MB (sometimes that work).

Method 3

For some, it works by updating the .htaccess file which you can find in the root directory. You can increase the maximum upload size in WordPress. Edit the .htaccess file in your WordPress site’s root folder and add the following code:-


php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300

Again, do note that if you are on a shared hosting package then these techniques may not work. In that case, you would have to contact your web hosting provider to increase the limit for you.

We hope this article helped you increase the maximum file upload size in WordPress.

If you need any further assistance, just drop me a message in the comments below!

It’s good to share

How to Add Additional File Types to be Uploaded in WordPress

Due to security reasons, WordPress only allows you to upload the most commonly used file types. By default, you can upload commonly used image formats, audio/video and documents using the default media uploader. But what if you wanted to upload a file type that is not allowed? In this article, we will show you how to add additional file types to be uploaded in WordPress.

If the above error looks familiar to you, then you’re at the right place.

File Types Allowed for Upload in WordPress

WordPress allows you to upload most common image files, audio/ video, PDF, Microsoft Office and OpenOffice documents. WordPress codex has a full list of allowed file types and extensions.

Adding Exceptions for Additional File Types

Security is the main reason behind the limitation on file types that users can upload. However, this does not mean that users cannot change this. Using a bit of code, you can add a new file type and extension to WordPress.

For example, add this code in your theme’s functions.php file or a site-specific plugin to allow SVG file type to be uploaded:-


function my_myme_types($mime_types){
    $mime_types['svg'] = 'image/svg+xml'; //Adding SVG extension
    return $mime_types;
}
add_filter('upload_mimes', 'my_myme_types', 1, 1);

Notice that the file extension goes as the key in $mime_types associated array and the mime type goes as its value.

In this example, SVG file extension represents files with the mime type image/svg+xml. You can find out mime types of several common file extensions on this page.

You can also add multiple file types in one code snippet, like this:-


function my_myme_types($mime_types){
    $mime_types['svg'] = 'image/svg+xml'; //Adding svg extension
    $mime_types['psd'] = 'image/vnd.adobe.photoshop'; //Adding photoshop files
    return $mime_types;
}
add_filter('upload_mimes', 'my_myme_types', 1, 1);

Awesome, now you can upload as many different file types as you like!

One other issue you may encounter is that you get a warning saying that the file “exceeds the maximum upload size for this site” as shown below:-

To resolve this issue please see the following article; WordPress troubleshooting guide to fix it.

If you need help with anything WordPress related, just drop me an email at [email protected] or leave a comment below.

It’s good to share

WordPress Version 5.2

On May 7, 2019, WordPress 5.2 “Jaco”, named for the jazz musician Jaco Pastorius, was released to the public.

As always, you can update your WordPress to the latest version or download the latest files from WordPress.org.

So what’s new with the latest version?

Site Health Check

Building on the Site Health features introduced in 5.1, this release adds two new pages to help debug common configuration issues. It also adds space where developers can include debugging information for site maintainers. Check your site status by going to Tools > Site Health, and learn how to debug issues.

WordPress 5.2 - Site Health

PHP Error Protection

This administrator-focused update will let you safely fix or manage fatal errors without requiring developer time. It features better handling of the so-called ‘white screen of death,’ and a way to enter recovery mode, which pauses error-causing plugins or themes.

WordPress 5.2 - Site Protection

Improvements for Everyone

Accessibility Updates

A number of changes work together to improve contextual awareness and keyboard navigation flow for those using screen readers and other assistive technologies.

New Dashboard Icons

Thirteen new icons include Instagram, a suite of icons for BuddyPress, and rotated Earth icons for global inclusion. Find them in the Dashboard and have some fun!

Plugin Compatibility Checks

WordPress will now automatically determine if your site’s version of PHP is compatible with installed plugins. If the plugin requires a higher version of PHP than your site currently uses, WordPress will not allow you to activate it, preventing potential compatibility errors.

Developer Happiness

As always, a large handful of developer-focused changes have also been made. The highlights of these include:

PHP Version Bump

The minimum supported PHP version is now 5.6.20. As of WordPress 5.2, themes and plugins can safely take advantage of namespaces, anonymous functions, and more!

Privacy Updates

A new theme page template, a conditional function, and two CSS classes make designing and customizing the Privacy Policy page easier.

New Body Tag Hook

5.2 introduces a wp_body_open hook, which lets themes support injecting code right at the beginning of the element.

Building JavaScript

With the addition of webpack and Babel configurations in the @wordpress/scripts package, developers won’t have to worry about setting up complex build tools to write modern JavaScript.

And plenty of more which you can read about here.

What we can do for you!

As always, it’s always best to keep your WordPress version and plugins up to date and use plugins from reliable authors that maintain their plugins. If you need assistance with upgrading your WordPress version, plugins, updating core code to be compatible with the latest versions of PHP (recommended) or anything else WordPress or digital related then get in touch by sending an email to [email protected]om. We &hearths; WordPress and as specialists in the field; you can guarantee that you are in very capable hands.

Have a look at out portfolio – if it’s a web specialist you require; we’re here at your disposal ; )

It’s good to share

The Journey – Hi Ho Silva Lining…

If you would like to read about my freelance journey, you can read the full story here.

No time for the full story? No problem! You can see a visual synopsis below…

Silva Web Designs - Journey - The Struggle...

Silva Web Designs - Journey - Beaches

Silva Web Designs - Journey - Our Portfolio

Silva Web Designs - Journey - What we love - WordPress

Nathan da Silva
Founder | Silva Web Designs

‘‘ The Crazy & Creative Team ’’

 

M: +44 7511 68 1818
W: silvawebdesigns.com
E: [email protected]

If you’re a music lover, follow our Spotify playlist; maybe we’re on the same wavelength.

It’s good to share