In this knowledgebase article, we’ll show you how to automatically set focus keywords from your ACF fields.
You can easily add more data and information to your pages and blog posts by using Advanced Custom Fields with Rank Math. Additionally, Rank Math and Advanced Custom Fields are easily integrated.
1 Navigate to the Theme File Editor
At first, navigate to the Theme File Editor from your WordPress dashboard. To do so, navigate to Appearance → Theme File Editor (for a Classic Theme) inside your WordPress admin area.
2 Add the Code Snippet
To update the focus keyword using the ACF field, add the below code snippet to your theme’s rank-math.php file.
function update_focus_keywords() {
$posts = get_posts(
array(
'posts_per_page' => -1,
'post_type' => 'post', // replace post with the name of your post type.
)
);
foreach ( $posts as $p ) {
// Replace 'article_topic' with your ACF field name.
if ( ! get_post_meta( $p->ID, 'rank_math_focus_keyword', true ) && function_exists( 'get_field' ) && ( null !== get_field( 'article_topic', $p->ID ) ) ) {
update_post_meta( $p->ID, 'rank_math_focus_keyword', strtolower( get_field( 'article_topic', $p->ID ) ) );
}
}
}
add_action( 'init', 'update_focus_keywords' );
In the above code snippet, you need to change the article_topic
field with your ACF field name. This field is used in two places in the code.
This code works only for published articles. The code checks if the focus keyword is set for a post. Then it checks if the ACF field is set (you can change this field name).
If the Rank Math focus keyword is not set, the above code automatically updates the focus keyword from the ACF field value.
3 Update the File
Once you’ve added the code snippet, click on the Update File button to save the changes made to the file.
Once the snippet code has been added, the end result will look like this:
If you still have questions – you’re always more than welcome to contact our dedicated support team. We’re available 24/7, 365 days a year…