0

I am looking to implement a basic check on my ACF field. I have an ACF field called Featured Article on all my custom post-type articles. It's a simple switch allowing for on, off functionality. I want to allow a max of 3 articles at the same time with the on setting, to display at most 3 articles to the user on the front-end.

For this functionality I have to write some code that checks for the setting on the backend on all the articles. For example, when the user is on a fourth article and switches the select of the ACF to on, there should be an error of sorts that says "you already have three other articles selected. Ideally, it would somehow gather the titles of the other articles and allow a quick switch-off for those.

I understand that this would be adding a lot of custom features to the WP backend, so let's start with the basics. How do I enable the ACF field to cross-check for the value of all other articles?

0

The only way I can think of to do it would be using the save_post action hook. Since your article isn't being saved through AJAX, and only when you actually save the post, that would be the best place, in my opinion.

I honestly haven't written a lot of error messages, so this might be wonky and probably won't work out of the gate, but I started with this article from SitePoint.

add_action( 'save_post', 'my_save_post_function' );
function my_save_function( $post_id ) {
    $error = false;

    $featured = get_posts(array(
        'meta_query' => array(
            array(
                'key' => 'featured_article',
                'compare' => '=',
                'value' => '1'
            )
        )
    ));

    if ( count($featured) > 3 ) {
        $error = new WP_Error('too_many_featured_articles', 'There are too many featured articles.');
        // You could use this error to list the titles and links to edit all of the other current featured articles.
    }

    if ($error) {
        // Here is where you would unset the ACF field, if you wanted.
    }

    return true;
}

This isn't meant to get you through the whole thing, but hopefully it's a good starting point for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.