Get WordPress Posts by ACF Field

Get WordPress Posts by ACF Field

Advanced Custom Fields (ACF) Fields are stored on a post as ‘meta_data’ and as such the solution to get posts by ACF Field is to get the post by its meta data. In this article I’ll show you 3 ways to do this.

Quick Links

Get WooCommerce Orders by ACF Field

WooCommerce orders are saved in the WordPress database as posts in the wpprefix_posts table and have a particular ‘post_type’ of ‘shop_order’.

If you have added an ACF Field to WooCommerce Orders then these will be saved on the post as ‘meta_data’ which is the standard WordPress way of adding custom data to posts for your own project needs.

WooCommerce gives us a specific function for getting orders and a way to fairly easily collect these by the ACF Field aka post ‘meta_data’.

Step 1:

You need too explicitly tell WooCommerce to search by your chosen meta value by inserting this code into your functions.php file before you can go ahead and actually perform the search. This is slightly annoying Id say but thats the way it works.

IMPORTANT: Change the highlighted values below to match those of your specific custom meta value name.

PROTIP: You can get the name of the ACF Field (which you would then replace the terms ‘customMeta’ with in the code example below) by looks at the ACF Field itself in your WordPress CMS

function searchCustomMeta( $query, $query_vars ) {
	if ( ! empty( $query_vars['customMeta'] ) ) {
		$query['meta_query'][] = array(
			'key' => 'customMeta',
			'value' => esc_attr( $query_vars['customMeta'] ),
		);
	}
	return $query;
}
add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', 'searchCustomMeta', 10, 2 );

Step 2:

In your theme or plugin use the WooCommerce native function as below to get your orders by meta value. You will obviously want to replace the highlights acfFieldName below but also the ‘somevalue’. Once WooCommerce has been set up to know the name of your custom data (step 1 above) its very easy to search for it.

PROTIP: You need to add each ACF Field Name you want to search by in step 1 above by visiting the ‘Custom Fields’ tab in your WordPress CMS at a URL which will be similar to https://yoursite.com/wp-admin/edit.php?post_type=acf-field-group. Then click on the specific field you are searching for and then look for the ‘Name’ attribute which will be one of the column names you can view there.

$orders = wc_get_orders( array( 'acfFieldName' => 'someValue' ) );

Get Posts by ACF Field using WordPress Native Functions

This code block gets posts which have a specific meta data name (key) of ‘acfFieldName‘ and values of Ferrari, Porsche and Toyota. You could add just one if you were looking for only one.

PROTIP: You need to add each ACF Field Name you want to search by in step 1 above by visiting the ‘Custom Fields’ tab in your WordPress CMS at a URL which will be similar to https://yoursite.com/wp-admin/edit.php?post_type=acf-field-group. Then click on the specific field you are searching for and then look for the ‘Name’ attribute which will be one of the column names you can view there.

Note: The compare part of the meta_query has various options which you can read about here in the WordPress Developer Docs for this function.

The code then loops through the results and prints out the status of each one. Change the code within the loop and in the $loop variable as you desire.

$loop = new WP_Query( array(
		    'post_type'         => 'shop_order',
		    'posts_per_page'    => -1, // change to however many you want. -1 will get all of them
                    'meta_query' => array(
		        array(
			    'key' => 'acfFieldName', // the name of the ACF Field
			    'value' => array( 'Ferrari', 'Porsche', 'Toyota' ),
			    'compare' => 'IN',
		        )
	            )
		) );

		// The WordPress post loop
		if ( $loop->have_posts() ): 
			while ( $loop->have_posts() ) : $loop->the_post();

			// do some code here for eg
                        echo $loop->post->post_status; // will print out the status of this order                     eg 'processing' or 'complete' or whatever

			endwhile;

			wp_reset_postdata();

		endif;

Get Posts by ACF Field using RAW SQL

As ACF Fields are stored as ‘meta_data’ on a WordPress Post we are going to give you some code which allows you to get a post by its meta_data field.

PROTIP: Replace the highlighted meta kay name with the Name of the ACF Field.

PROTIP: You can find the Name of the ACF Field at this address in your CMS, https://yoursite.com/wp-admin/edit.php?post_type=acf-field-group

global $wpdb;
$results = $wpdb->get_results( "
        SELECT pm.meta_value AS user_id, pm.post_id AS order_id
        FROM " . $wpdb->prefix . "postmeta AS pm
        LEFT JOIN " .$wpdb->prefix . "posts AS p
        ON pm.post_id = p.ID
        WHERE p.post_type = 'shop_order'
        AND pm.meta_key = 'acfFieldName'
        AND pm.meta_value = 'someValue' // you could remove this line if you just want all posts by the acfFieldName
        ORDER BY pm.meta_value ASC, pm.post_id DESC",
        OBJECT );

foreach($results as $result){
        echo $result->post_title; 
}

Learn WordPress customization throughly with an online course at Udemy

If you are having difficulty understanding this tutorial and then I suggest you start from scratch with WordPress in general. The best way to learn is with a better all around general understanding of WordPress. Check out some of the courses on Udemy related to WordPress. They cover developer level courses and more non-dev CMS editor type tutorials as well.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *