Depending on where you are with your current WordPress Challenge (be it this #2 one or something else), I wanted to share a few tips that are somewhat related to the WordPress Challenge #2.

Enqueueing Scripts & Styles conditionally

This is a lesson I always like to teach others because it’s really important. Knowing how to load styles & scripts properly makes WordPress sites more optimized from the start.

So, let’s get to it.

Enqueue Scripts & Styles conditionally on front:

post_content, 'contact-form-shortcode' ) ) {
   return;
 }

 // Here, I can enqueue scripts and styles.
}

Enqueue Scripts & Styles conditionally on admin:

In the admin area, we can check if the user is on our settings page or a page where we have our content displayed. You can easily check that by doing die($hook); in there and reloading the page where our content is. It will show you the hook you can use.

Contact Form - Fields configuration

Let’s now see how you could have your field configurable so you can render more fields in your contact form.

Shortcode approach

Let’s imagine we have an attribute “fields” in the shortcode. And we allow a simple way of defining them such as this:

[contact-form fields=Name|text,Email|email,Age|date]

Then inside of the function that renders the shortcode, you use that attribute and reconstruct it into fields:

This way, you could extend that to allow more options in there, so the 3rd element of each field would be options for dropdown or something like that. Maybe the name of the field that is sent when posted.

Filter approach

Another, more “sexy” way, of handling this is to have fields defined in a function. Then those fields are filtered so you can add more fields.

 [
      'type' => 'email',
      'name' => 'email',
      'label' => __( 'Email', 'textdomain' ),
      'validate' => 'function_to_validate'
    ]
  ];
  
  return apply_filters( 'my_contact_fields, $fields );
}

add_filter( 'my_contact_fields', 'add_name_field_to_fields');

function add_name_field_to_fields( $fields ) {
  $fields['name'] = [
    'type' => 'text',
    'name' => 'name',
    'label' => __( 'Name', 'textdomain' )
  ];
  return $fields;
}

In the above example, you can see now how contact form fields are extensible and another plugin can be used to add more fields to it.

In case you have each contact form saved inside of a database (as a CPT or similar), you can pass an ID to the function for fields. So fields can be filtered out, depending on the contact form ID.

Conclusion

Hope you’ve learned something new or that I was able to give you more ideas on how to solve a part of your coding challenges.

More from me:

Newsletter on Freelancing: https://ibenic.com/newsletter

WordPress/Dev Tutorials: https://ibenic.com/

Reply

Avatar

or to participate

Keep reading