If you are seeing an allowed memory size exhausted error in WordPress? This is one of the most common WordPress errors, and you can easily fix it by increasing the php memory limit in WordPress. In this article, we will show you how to fix WordPress memory exhausted error by increasing PHP memory.

What is WordPress Memory Exhausted Error?

WordPress is written in PHP server-side programming language. Every website needs a WordPress hosting server for it to function properly.

Web servers are just like any other computer. They need memory to efficiently run multiple applications at the same time. Server administrators allocate specific memory size to different applications including PHP.

When your WordPress code requires more memory than the default allocated memory, you get to see this error.

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 2348617 bytes) in /home4/xxx/public_html/wp-includes/plugin.php on line xxx

The error can occur in a number of different circumstances. However, it’s most likely to arise when you take specific types of actions on your site, such as:

  • Installing and activating a new theme or plugin.
  • Uploading images and other media to your site.

If you’ve run into this error on your own WordPress site, don’t worry. The reasons behind it are simple – let’s talk a little more about why it occurs.

Increasing the WordPress Memory Limit

To address memory limit issues, there are two paths:

  • Adjust yourself
  • Contact your hosting company

Do It Yourself

To adjust on your own, here are some methods to try. Be aware that this section requires advanced knowledge; it is not basic.

Edit your wp-config.php file

Add this to the top, before the line that says, “Happy Blogging”:

define('WP_MEMORY_LIMIT', '256M');
WordPress memory can be different from the server – you need to set this regardless of server memory settings

http://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP

Edit your PHP.ini file

If you have access to your PHP.ini file, change the line in PHP.ini
If your line shows 64M try 256M:

memory_limit = 256M ; Maximum amount of memory a script may consume (64MB)

Edit your .htaccess file

If you don’t have access to PHP.ini try adding this to an .htaccess file:

php_value memory_limit 256M

Contact Your Host

Should you not feel comfortable in trying the above methods, or the above did not work for you, you need to talk to your hosting about having them increase your memory limit.

Reference:

https://www.wpbeginner.com/wp-tutorials/fix-wordpress-memory-exhausted-error-increase-php-memory/

https://woocommerce.com/document/increasing-the-wordpress-memory-limit/

https://kinsta.com/knowledgebase/wordpress-memory-limit/

contact-form-7

How To Fix Contact Form 7 Error: Email not sending

Contact form 7 is a free WordPress plugin that helps you to easily create forms and place them anywhere on your website. Contact form 7 is one of the most widely used plugins on WordPress with over 5 million active downloads. However, I have found that some of the forms sometimes may stop working or have problems when trying to send a message. Most times you will get a message with a colored border saying “An error occurred while trying to send your message. Please try again later.”

Depending on the color of the border surrounding the message, it will determine the fixes we needed.

If you have the Yellow message, scroll to this section.

If you have the Orange message, scroll to this section.

If you have the Red message, scroll to this section.

Yellow Error Message Fix

The yellow error tells us that there is an error with form validation. This will be something we need to change in the admin area.

Forms Not Validated

Go to your WordPress admin dashboard and you will see icons on the Contact Form 7 plugin menu. Click on the “Contact Forms” menu so that we see the error in detail:

Once you get to the forms page, near the top you will see an error message like the image below. Click on the link within this message to fix the problem.

That page will take you to another page where you just need to simply click on the “validate form now” button.

This should fix the problem, but if not, then try other ways.

Orange Error Message Fix

The orange error tells us that your form isn’t sending because of a spam issue. Here are two solutions I did to fix this problem.

ReCaptcha v2

Contact Form 7 uses reCaptcha to make sure your website doesn’t receive a lot of spam. Once CF7 moved from reCaptcha V2 to V3, forms stopped working. The easiest solution that instantly fixed these issues for me was to change the reCaptcha back to V2. Here is what I did…

Go to the plugins page and search for “Contact Form 7 – reCaptcha v2“, install and activate it.

Next go to reCaptcha version and select Version 2.

Next go to the Contact Form 7 tab and click on integration. Click on “remove keys”.

Next go to the Google reCaptcha page, sign in and create new site keys for your website. You might need to delete your website property from reCaptcha first. When asked for reCaptcha type, choose reCaptcha V2.

Once the keys have been generated go back to the integrations tab for Contact Form 7 and add your new V2 site keys.

Once you are done, click save then go back to your forms and add the “[recaptcha]” shortcode.

Red Error Message Fix

The red error tells us that the form is not sending and is caused by your server not sending the email.  There are two solutions for this:

Contact Hosting Company

Contact your hosting company and tell them about the issue. They will most likely test the email function on your server and fix it or they will not have a solution which will bring me to the next fix.

Install SMTP Plugin

SMTP and php mail plugins make sure emails are authenticated and properly sent through third parties. The plugin I use to fix this was WP Mail SMTP you can use other SMTP plugins like Post SMTP.

Once you downloaded and activate WP Mail SMTP, go to the settings page.

Go to one of the suggested mailers websites and sign up for an account. I’ve used Sendingblue, Google and SendGrid in the past. Once you create an account you will get an API key(s) and you will need to go back to that SMTP plugin settings page to enter your API keys. You will see a place to enter your credentials (see image below). This will appear below the mailer options on the SMTP settings page.

Once your API key is saved, go to the top of this page and you will see an option to send a test email.

Send a test email to make sure everything is working.

Other Things To Try

Caching plugin Conflicts

Another reason why your contact forms may not be sending messages is from caching plugins conflicts. The easiest way to test for this is to deactivate your cache plugin and try testing the form again. If it works, then you either need to find another cache plugin that doesn’t cause issues.

Still not working?

A while back I noticed that contact form 7 often had these annoying issues and they happened every time I updated the plugin.  If you are frustrated with this plugin, you should switch to a another or a premium plugin as they usually come with support so you could get your issues fixed quickly.

Override WooCommerce Template Files

How to Override WooCommerce Template Files

WooCommerce is a popular e-commerce plugin for WordPress that provides a wide range of features and functionality to create online stores. One of the advantages of using WooCommerce is the ability to customize the appearance and layout of your store’s front-end by modifying the template files. In this article, we will explore the process of overriding WooCommerce template files in a professional and upgrade-safe manner.

WooCommerce templates serve as the backbone of the front-end presentation of your online store. By editing these files, you can modify the markup and structure of various pages, such as product listings, cart pages, and checkout pages. However, it’s important to follow best practices to ensure that your customizations are not lost during plugin updates.

To override WooCommerce templates, it is recommended to use a child theme, which is a separate theme that inherits the functionality and styling of its parent theme. This allows you to make modifications without directly editing the parent theme files, which can be overwritten during theme updates.

Here is a step-by-step guide to overriding WooCommerce template files:

  1. Create a child theme: If you haven’t already, create a child theme for your WordPress site. This involves creating a new theme directory and a style.css file with the necessary information to identify it as a child theme.
  2. Locate the WooCommerce template file: Identify the template file you want to modify. You can find the default WooCommerce template files in the following directory: /wp-content/plugins/woocommerce/templates/.
  3. Copy the template file: Using a file manager or FTP, navigate to the WooCommerce templates directory and locate the file you want to override. Copy this file to the corresponding directory within your child theme. If the directory doesn’t exist, create it. For example, if you want to modify the archive-product.php file, copy it to /themes/your-child-theme/woocommerce/archive-product.php.
  4. Make desired changes: Open the copied template file in a text editor and make the necessary modifications to the markup, structure, or content. For instance, you can add custom notices, rearrange elements, or apply styling changes.
  5. Save and upload: Save the modified template file and upload it back to the child theme directory, overwriting the existing file.

By following these steps, you have successfully overridden a WooCommerce templates, ensuring that your customizations will persist even after plugin updates.

It’s worth noting that WooCommerce templates are organized in a hierarchical structure, allowing you to override specific files for different pages or elements. By replicating the directory structure in your child theme’s WooCommerce directory, you can override templates for specific purposes.

Override example: Let’s consider an example where we want to add a notice to the price template on the single product page. Locate the price.php template file in the WooCommerce plugin directory: woocommerce/templates/single-product/price.php. Copy this file to your child theme’s directory: your-child-theme/woocommerce/single-product/price.php. Open the copied file and make the desired changes. In this case, we will add a notice about the price, such as excluding tax and shipping:

<?php

/**
 * Single Product Price
 */

global $post, $product;

?>
<p itemprop="price" class="price"><?php echo $product->get_price_html(); ?></p>
<p>Notice: price shown excludes tax and shipping.</p>

By utilizing this approach, you can override various aspects of the WooCommerce front-end UI, including HTML email templates, in a manner that minimizes the risk of losing your customizations during plugin updates.

In conclusion, overriding WooCommerce templates allows you to have full control over the appearance and structure of your online store. By following the recommended method of using a child theme, you can make modifications in a professional and upgrade-safe manner. Remember to carefully organize your custom templates within the child theme’s WooCommerce directory to target specific elements or pages. With these techniques, you can create a unique and tailored shopping experience for your customers using WooCommerce.

Resources:

https://woocommerce.com/document/template-structure/
https://www.godaddy.com/garage/how-to-override-woocommerce-template-files/
https://www.templatemonster.com/help/woocommerce-how-to-override-woocommerce-temlates-files.html

Elementor acquires Strattic

Elementor acquires Strattic, the leading WordPress static hosting solution for secure, high-performance websites. This decision strengthens our ability to provide an end-to-end solution to millions of Web Creators by harnessing the power of static hosting technology and marks a significant milestone for Elementor.

Israeli company Elementor, the developer of a building platform for WordPress websites, has acquired Strattic, a web development and hosting solutions outfit based in Jerusalem, in an all-Israeli deal announced on Wednesday. Calcalist said the transaction was estimated at “several million dollars.”

Founded in 2016 by Yoni Luksenberg and Ariel Klikstein, Elementor’s open-source, drag-and-drop platform allows web creators to build code-free WordPress-based sites. The no-code website building concept is similar to what Israeli company Wix created — just for WordPress, the global leader in content management systems (CMS).

Strattic was founded in 2018 by Josh Lawrence and Miriam Schwab, a web developer with years of experience with WordPress sites, who set out to solve the “noise” around managing and securing WordPress sites.

Schwab has said WordPress was the best website and content management system out there but managing the life cycles of WordPress sites can be time-consuming and cumbersome, demanding solutions to issues of security, performance and reliability — challenges she experienced first-hand as a web developer.

Since its founding in 2018, Strattic has spearheaded static architecture to run stable and reliable websites, making downtime a relic of the past and allowing for seamless scale. Websites running on Strattic are renowned for their lightning-fast website speeds no matter where visitors are in the world, as it uses pre-rendered static pages that are fully served by a CDN.

With static hosting, users can deploy their dynamic WordPress websites as static HTML/CSS replicas to global CDN networks, which drastically improves the performance of their sites and eliminates potential security vulnerabilities and site breakdowns during updates. With a dramatically reduced attack surface, WordPress vulnerabilities become irrelevant as security is no longer a defensive endeavor.

I firmly believe that Strattic’s technology, know-how, talent, and established market position as the leader of this technology in the WordPress space will allow us to offer the benefits of static hosting to the entire Elementor community and provide a platform for hosting ultra-performant large-scale websites — all in one place.

Elementor + Strattic = visions aligned

The value that Elementor brings to Web Creators aligns with our vision: removing the noise around managing WordPress so users can enjoy all the benefits that WordPress has to offer and focus purely on their work. With Elementor, that means Web Creators can easily build out new page layouts and designs and get content out there faster. With Strattic, developers and DevOps professionals can focus on their main responsibilities and stop worrying about the WordPress infrastructure of the company’s website and all that entails.

Between our aligned visions, passion for WordPress, and shared histories, joining forces with Elementor feels like a match made in heaven. We are very excited to see what we can accomplish together on this next stage of our journey.

The Future of WordPress Is High-Performing, Ultra-Secure, and Hyper-Stable Websites

elementor

Elementor has pioneered website design and building standards as WordPress’ fastest-growing web creation platform for the past six years, keeping in line with our founding vision of empowering web creators.

After years of powering millions of websites with our famous editor plugin, we remain committed to solidifying Elementor as the world’s best editor, while breaking new ground in delivering innovative experiences in designing, developing, and building the web.

With Elementor now behind them, the Strattic team, led by Miriam and Josh, will work with us to bring the static experience to millions of WordPress and Elementor users. This milestone is another step towards our shared vision of building the perfect platform for web creators.

What does this mean going forward?

Strattic will continue to provide you with a fast, secure and scalable solution for your WordPress website, with a continued fanatical commitment to excellent customer support. At the same time, joining with Elementor means we will be able to provide you with even more innovation in the static WordPress space and bring our vision to millions of users.

Resources:

https://elementor.com/blog/elementor-acquires-strattic/
https://www.strattic.com/strattic-acquired-by-elementor/
https://www.calcalistech.com/ctechnews/article/bjdyl0t005
https://www.timesofisrael.com/wordpress-site-builder-elementor-buys-strattic-in-all-israeli-deal/

Welcome to WordPress 6.0 “Arturo”

Say hello to “Arturo” and WordPress 6.0, inspired by Grammy-winning jazz musician, Arturo O’Farrill. Known for his influence on contemporary Latin jazz, Arturo has pressed more than 15 albums spanning a body of work across five decades.

What’s Inside

Enhanced Writing Experience

Writing improvements abound, whether you’re writing a brand new post or adding elements to an existing page. Explore more ways to streamline your content creation process, including:

  • Select text across multiple blocks for easier copying and pasting.
  • Type two open brackets `[[` to quickly access a list of recent posts and pages.
  • Keep existing styles when you transform some blocks from one kind to another—from a Paragraph block to a Code block, for instance.
  • Create customized buttons and any new buttons you make will retain the style customizations automatically.
  • Make tag clouds and social icons even more appealing with updated settings and controls, and a new outline style for the tag cloud.

Style Switching

Block themes now include the option to contain multiple style variations. This expands the new Style system even further and enables shortcuts to switch the look and feel of your site all within a single theme. In block themes that support this feature, you can change both the available settings, like the font-weight, and the style options, like the default color palette. Change the look and feel of your site with just a few clicks.

Style-switcher

More Template Choices

WordPress 6.0 includes five new template options for block themes: author, date, categories, tag, and taxonomy. These additional templates provide greater flexibility for content creators. Tailor each with the tools you already know or with the following new options in this release:

  • Featured images can be used in the cover block.
  • New featured image sizing controls make it easier to get the results you want.
  • While editing a template, at the root, or between blocks, the quick inserter shows you patterns and template parts to help you work faster and discover new layout options.
  • The query block supports filtering on multiple authors, support for custom taxonomies, and support for customizing what is shown when there are no results.

Integrated Patterns

Patterns will now appear when you need them in even more places, like in the quick inserter or when creating a new header or footer. If you’re a block theme author, you can even register patterns from the Pattern Directory using `theme.json`, enabling you to prioritize specific patterns that are most helpful to your theme’s users.

Additional Design Tools

Design tools grow more powerful and intuitive with each release. Some highlights for 6.0 include:

  • A new color panel design saves space, but still shows your options at a glance.
  • New border controls offer a simpler way to set your border exactly as you like it.
  • Transparency levels for your colors allow for even more creative color options.
  • Control gaps, margins, typography, and more on a collection of blocks, all at once, in the Group block.
  • Switch between stack, row, and group variations to position groups of blocks with more layout flexibility.
  • Use the gap support functionality in the Gallery block to create different looks – from adding spacing between all images, to removing spacing altogether.

Better List View

New keyboard shortcuts enable you to select multiple blocks from the list view, modify them in bulk, and drag and drop them within the list. List View can be opened and closed easily; it comes collapsed by default and it automatically expands to the current selection whenever you select a block.

Block Locking Controls

Now you can lock your blocks. Choose to disable the option to move a block, remove a block, or both. This simplifies project handover, allowing your clients to unleash their creativity without worrying about accidentally breaking their site in the process.

Improved Performance

This release includes several updates focused on improving the performance of WordPress. These enhancements cover a range of performance areas including improving the page and post-load speed, reducing the execution time of various query types, caching, navigation menus, and much more. The performance team working group is an important focus area of the core development team. For more information on this group’s work, please follow their work on Making WordPress with the #performance hashtag.

Enhancing Accessibility

Accessibility is an integral part of the WordPress mission of fostering an inclusive community and supporting users of all types around the world. With this in mind, WordPress 6.0 includes more than 50 updates specifically focused on enhancing the accessibility of the platform. You can read about these updates and learn more about the accessibility initiatives that are ongoing.

Learn More About WordPress 6.0

https://wordpress.org/news/2022/05/arturo/
https://www.wpbeginner.com/news/whats-new-in-wordpress-6-0-features-and-screenshots/
https://www.bluehost.com/blog/wordpress-news-roundup-may-2022/
https://kinsta.com/blog/wordpress-6-0/
https://www.dreamhost.com/blog/wordpress-6-0/

WordPress Theme Development Resources

WordPress Theme Development Resources:

You know HTML, CSS, and JavaScript. You can make beautiful websites. Maybe you’ve heard about WordPress, but aren’t entirely sure how to implement it, or why you might need it. Maybe a client asked for WordPress, but you’re not really familiar with it. Maybe you’ve worked with it before, but don’t know how to make your own theme from scratch. Below is a list of general resources related to WordPress theme development, such as tutorials, tools, and more.

PREREQUISITES

All you need to start is a website. Any website will do. You don’t need to know any PHP, or have any prior experience with WordPress. Your website can be custom, or built on Bootstrap/some other framework.

Tutorials:

The official WordPress Theme Development Handbook that covers everything.

A 3-part tutorial series that includes pagination, comments, functions, meta boxes, and more.

Covers the fundamental logic of themes such as hierarchy, processing posts, and using functions.php.

A comprehensive course that that teaches everything from common functions to widgets and menu areas.

This tutorial literally starts from scratch with zero lines of code and finishes with a working theme.

Starts from the beginning and teaches how to develop a WordPress theme using Bootstrap markup.

Digs into the inner workings of a common WordPress theme and things to consider when creating a theme.

Covers the basics of theme development and more advanced topics including PHP and building plugins.

Examples:

A section from the official WordPress Theme Development Handbook that showcases various examples.

Tools:

An older helper plugin that checks, recommends, and installs WordPress developer plugins.

A plugin that validates if a theme is in accordance with the latest theme review standards.

Provides an impressive amount of information about a WordPress installation.

Regenerates thumbnail sizes for one or more images contained in the Media Library.

Allows the debugging of HTTP API calls, Ajax calls, REST API calls, and more.

An older plugin that adds a debug menu to the admin bar with various functions.

Displays useful info such as post/page ID, taxonomy terms, and various slugs.

An older plugin that tests the direction of text from left-to-right to right-to-left.

Other:

Includes various tips and tricks to help you become a better theme developer.

As the title states, some of the most common theme development mistakes and how to avoid them.

Problem: You want to create a simple new WordPress theme but all the tutorials you’ve seen are way too complex or don’t fit in at all with the existing WordPress look.

Solution: We’ve come up with a simple, useful list you can use for your next theme!

This list is constantly growing and we welcome your recommendations! Please consider contacting us if you’d like to suggest a new resource. Thank you!

Conclusion: If you’re starting out building WordPress themes or want to develop a system for building them more efficiently or robustly, how do you decide which approach to take? In this article, we have briefly listed resources about how WordPress themes work and then look at some of the different approaches to developing them from scratch. If you’ve found any trouble, or have any additional information that would make this better or more simple to understand, please let me know!

wp-category

Categories are a very important feature of any WordPress website. They are very helpful to maintain or browse a website. They tell you what’s related to what and they give your visitors a good way to browse your site. But sometimes they are not serving your URL structures. Then what should you do?

Don’t worry guys we have are here to help. Today we are going to show how to fix this. Meanwhile you may also interested in 20 Reasons Why You Should Use WordPress For Your Website

So, there are different ways to achieve the same and we are going discuss them one by one.  Just remember that if you have a fresh WordPress installation then set up permalinks as you want. But if you are changing permalinks structure on a live website, do properly, redirect old URLs to new ones to avoid loses.

Remove Category from WordPress URLs with a Dot

  1. Go to Settings -> Permalinks.
  2. Select Custom Structure and put /%category%/%postname%/ there.
  3. Assign a dot to the Category base field and save the change.

The below picture will help you to understand.

Please remember that providing dot to Category base in settings is a must. As leaving it blank will use the default value. Visit a post after saving settings and check the URL, it won’t have the category base now. While this trick currently works, there’s no assurance that it will work in the future as well.

Remove Category From Your URLs with .htaccess

RewriteRule ^category/(.+)$ http://www.yourwebsite.com/$1 [R=301,L]

You can also add this code to your .htaccess file through FTP rather than using a dot. Add the code before the closing </IfModule> tag in the file and it will remove the category slug from WordPress permalink.

What if I am using Yoast SEO Plugin

The current version of SEO by Yoast plugin has discontinued the option of category removal from URLs. The last version had the option in the Advanced menu of plugin settings. The websites, who are using Yoast for a long time, still have their URLs without the category base.

If you’ve installed Yoast plugin on your fresh WordPress website, check the post URLs as well. While we’re not sure, the feature might be still there and working silently. Else there are other plugins as well to remove category slug.

Removing Category from Slug using a Plugin.

The plugin ‘Remove Category URL’ is much popular and has additional advantages too. You can try the plugin if your website is older than 6 months. It will redirect the old category permalinks to the new ones, which is better for SEO. Also, you don’t need to configure anything or modify a file. Get the WordPress official plugin URL here.

Although you can always write a function for the functionality it makes the site slower. At last, all easy methods to remove the category slug from URLs are there. Do let us know in the comment section which one do you prefer.

 

WordPress Location-Based Search

Create a WordPress Location-Based Search:

Creating a location-based search feature for a WordPress website involves integrating geolocation functionality and customizing your search system to filter results based on user-provided or detected location data. Here’s a general guide to help you achieve this:

1. Using a plugin:

1. Choose a Geolocation Plugin: Start by choosing a suitable WordPress plugin that offers geolocation functionality. Some popular options include “WP Store Locator,” “GeoDirectory,” and “Locatoraid.”

2. Install and Activate the Plugin: Search for your chosen geolocation plugin in the WordPress plugin repository, install it, and activate it.

3. Configure the Plugin: Most geolocation plugins will have settings to configure how your location-based search works. You’ll need to set parameters such as map styles, location data input methods (manual entry or automatic detection), radius distance, and other relevant options.

4. Add Locations: If your website involves displaying specific locations (e.g., stores, events, properties), you’ll need to add these locations using the plugin’s interface. Typically, you’ll provide the location name, address, and potentially additional information like hours of operation or contact details.

5. Integrate Geolocation with Search: Depending on the plugin you’re using, it might have built-in shortcodes or widgets that you can use to display a search form with location-based options. If not, you might need to customize your theme’s templates or use a page builder to create a custom search page.

6. Customize the Search Form: Create a search form that includes a location input field along with other search criteria you want to offer. The location input could be a text field where users can type in their location or use a map-based picker if your plugin supports it.

7. Filter Search Results: Modify your website’s search functionality to consider the location parameter when querying your database for results. You’ll need to integrate the plugin’s geolocation functionality into your search queries. This might involve using hooks, filters, or custom code depending on your site’s setup and the chosen plugin.

8. Display Results: Once you’ve gathered location-based search results from your database, display them on your search results page. Depending on your design, you might want to show the results as a list, grid, or on a map.

9. Implement Maps (if needed): If your plugin supports it, you can integrate interactive maps into your search results page. This can help users visualize the location of search results more effectively.

10. Test Thoroughly: Testing is crucial to ensure that the location-based search functionality works as intended. Test it on various devices, browsers, and with different search scenarios to catch any potential issues.

Remember that this is a general guide, and the exact steps might vary based on the plugin you choose and your website’s specific requirements. Make sure to refer to the documentation of the geolocation plugin you’re using for more detailed instructions.

2. Custom Code

I’ve done this a few times in the past but yesterday I decided to write these notes for a colleague to show how to construct a location based search for a new WordPress site he is developing. Essentially to create a location search, in this case for Property sales, we need to override the standard WordPress search with our own custom query. The following is split into sections. It’s written mostly in note form but it should be easy enough to follow. If you have any questions by all means comment and I’ll answer as best as I can.

Data

Create a new custom post type called ‘property’ which will serve as the location for the data keeping it away from the other content on the site.

Custom fields

I use Advanced Custom Fields for all of my projects these days but by all means use your own plugin or method. As long as the data is stored in wp_postmeta then this tutorial is still valid. Create something similar to the following fields in your system. These aren’t really referenced specifically later on but are a good start for search fields for this sort of site.

  • Beds (select, fixed number of options)
  • Baths (select, fixed number of options)
  • Price (number field)
  • Address (separate fields unless you want to split them manually)
  • Type (select, predefined, multiselect?)
  • Status (select, predefined… under offer, sold, available?)

Custom data

On saving a new/exsiting property post type item you need to geocode the address and save the resulting latitude and longitude into the wp_postmeta table. Use the following page to help you with this:

https://codex.wordpress.org/Plugin_API/Action_Reference/save_post

Use the ‘book’ example looking for the ‘property’ post type almost verbatim. It will show you how to trigger a PHP function on the saving of a new or existing item of content using the correct post type. You then need to Geocode (convert to latitude and longitude) the address string from the POST array and save in postmeta per above. The following page will help you with that.

https://www.andrew-kirkpatrick.com/2011/10/google-geocoding-api-with-php/

If you aren’t familiar with how to save to postmeta then the following will help:

update_post_meta($post_id, 'latitude', $latitude);

Build the search form sidebar

This can be done either in raw PHP in sidebar.php (or somewhere in the theme) or as a widget (latter method preferred for sidebars as makes it portable). If widgets then the following will help significantly as the code sample is more or less exactly what you need:

https://codex.wordpress.org/Widgets_API

Copy the code from the section titled ‘Example’. This will register a widget on the system which you can drag into one or more sidebars in Appearance > Widgets

Setting up a sidebar is here:

https://codex.wordpress.org/Function_Reference/register_sidebar

If you are using the Bones theme (my preference) then it has several set up out of the box. A sidebar has a name which you use to put the contents onto the site. The code is simply:

dynamic_sidebar($sidebar_name);

It will echo by default and outputs nothing if no widgets so nice and easy really

Build the search form

You can do in HTML/CSS as normal hard coding the values of the search or pulling from $_GET which could be where you are advised to send the data through (means you can directly link via URL to a search result rather than POST which is less portable). The form action to use for a search in WP is /?s= which will activate the search template. ‘s’ is the querystring parameter for a search term. You can perform a search without it.. A handsome chappie wrote a code sample you can use:

https://www.sean-barton.co.uk/2012/05/wordpress-search-keyword

Perform the search

search.php in your theme powers the search results as you might know. The query itself can be done anywhere so use this for layout purposes. There should be ‘the loop’ in this file as normal which is designed for search results. Before ‘if (have_posts()): the_post();’ add a PHP function call or your own to something you have defined in functions.php or simply dump your search code into search.php.. there is no ‘wrong’ way to do it.

The trigger for the search is a WP function ‘query_posts()’. It will override the array of data that ‘has_posts’ has to work with and you can use the native output loop/functions to display the results.

Constructing a custom search would be a case of building an array and passing to query_posts. You can get most of the search done this way and then split into a bit of SQL perhaps for the location based side of things. I shall go into that later.

The resource you need to map the majority of the fields would be:

https://codex.wordpress.org/Class_Reference/WP_Query

WP Query is the class which WP uses at the back of query_posts but using the latter function sets up globals which make WordPress behave differently in ‘the loop’. For searching on data stored in postmeta you would need to use ‘meta_query’, taxonomies use ‘tax_query’ and general stuff like search you just pass as attributes to the array. Examples as follows which you can break down and use if you like:

function cf_custom_search_query() {
	global $wp_query; //not sure we need this
	
	$arr = array();
	
	$author = cf_get('author'); //cf_get is a wrapper on if (isset(something)) return something; else return false;
	$genre = cf_get('genre');
	$price_from = cf_get('price-from');
	$price_to = cf_get('price-to');
	
	$paged = get_query_var('paged'); //wp function. copy verbatim
	
	$arr['post_type'] = 'property'; //post type slub
	$arr['post_status'] = 'publish'; //published only as opposed to draft or private
	$arr['paged'] = $paged; //sets the page number to show.. just leave this as is
	
	$condition = array();
	
	foreach ($_REQUEST as $key=>$value) {
		if (substr($key, 0, 5) == 'cond-') {
			$condition[] = substr($key, 5); //for multi select checkboxes
		}
	}
	
	if ($val = cf_get('s')) {
		$arr['s'] = $val; //s is the actual search term
	}
	
	$meta_query = array();
	
	if ($price_from || $price_to || $author) { //meta query is for items in post_meta. we can only pass a single array although the array can have multiple conditions
		if ($price_from && $price_to) {
			$meta_query[] = array(
						'key'     => '_price',
						'value'   => array($price_from, $price_to),
						'type' => 'DECIMAL',
						'compare' => 'BETWEEN'
					);
		} else if ($price_from) {
			$meta_query[] = array(
						'key'     => '_price',
						'value'   => $price_from,
						'type' => 'DECIMAL',
						'compare' => '>='
					);
		} else if ($price_to) {
			$meta_query[] = array(
						'key'     => '_price',
						'value'   => $price_to,
						'type' => 'DECIMAL',
						'compare' => '<='
					);
		}

		if ($author) {
			$meta_query[] = array(
						'key'     => 'author',
						'value'   => $author,
						'type' => 'CHAR',
						'compare' => 'LIKE'
					);
		}
		
		if ($meta_query) {
			$arr['meta_query'] = $meta_query;
		}
	}
	
	if ($genre && $genre != '-') { //this is a custom taxonomy. so we pass the category slug (or an array of slugs) from a category.
		$arr['tax_query'][] = array(
			'taxonomy' => 'product_cat',
			'field'    => 'slug',
			'terms'    => $genre,
		);
	}
	
	if ($condition) { //as above. another custom taxonomy
		$arr['tax_query'][] = array(
			'taxonomy' => 'condition',
			'field'    => 'slug',
			'terms'    => $condition,
		);
	}
	
	if (!$sort = cf_get('sort_order')) {
		$sort = cf_session('sort_order', 'price_low');
	}
	
	if ($sort) {
		
		if ($sort == 'price_low' || $sort == 'price_high') {
			$arr['orderby'] = 'meta_value_num';
			$arr['meta_key'] = '_price';
			$arr['order'] = 'ASC';
			
			if ($sort == 'price_high') {
				$arr['order'] = 'DESC';
			}
		} else {
			$arr['orderby'] = 'title';
			$arr['order'] = 'DESC';
			
			if ($sort == 'abc') {
				$arr['order'] = 'ASC';
			}
		}
		
		$_SESSION['sort_order'] = $sort; //so it's saved for next time if they go elsewhere and come back
	}
	
	query_posts($arr); //performs the query and sets up the globals
}

Performing a location based search

On search we have ‘s’ or ‘location’ depending on how you built your form. Up to you which field you use but perform the same Geocode on the fly as you did for the save_post step above. This will give you a latitude and longitude to search on. To get into the actual SQL of a search you would want to implement something like the following:

https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where //to add to WHERE
https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join //to add to FROM

A handy usage conversation to help with the above:

https://wordpress.stackexchange.com/questions/75381/using-dynamic-conditions-in-posts-where-filter

This is a good resource giving you all of the filters you can use to get access to the SQL of the main query:

https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_clauses

Make sure to wrap your add_filter and remove_filter calls in is_search() which means you only require the LAT/LONG calculation to be done in search based queries.. or just only add/remove the filter in your search function defined in functions.php or search.php and only called on a search.. making sure to remove once used.

if (is_search()) { 
	add_filter('posts_where', 'my_posts_where'); 
	//.. and so on
	//perform search function
	remove_filter('posts_where', 'my_posts_where'); 
	//.. and so on 
}

The remove is just housekeeping, however, if you don’t remove the filter(s) then the next time you run query_posts in that same page load the same filters will be added which might mess with the result unexpectedly. To put this together you need to join in two instances of wp_postmeta or $wpdb->postmeta (in case wp_ is not the table prefix) making sure to alias uniquely:

add_filter('posts_join', 'my_posts_join');

function my_posts_join($sql) {
	$sql .= ' JOIN ' . $wpdb->postmeta . ' my_join1 ON (' . $wpdb->posts . '.ID = my_join1.post_id AND my_join1.meta_key="latitude");
	return $sql; 
}

And in posts_where:

add_filter('posts_where', 'my_posts_where');

function my_posts_where($sql) {
	$sql .= ' AND my_join1.value = "blah" '; //always start AND because it will be appended onto the main query and you can use the aliases defined in the post_join above
	return $sql; 
}

You can use the geocode values for the location entered via $_GET and then write the SQL to return the correct result based of something like this example:

https://developers.google.com/maps/articles/phpsqlsearch_v3

The section titled ‘Finding Locations with MySQL’ gives the query and some useful advice.

Get a brew and put your feet up!