Date

Category

Web Dev

Tags

Advanced Custom Fields is a versatile and powerful plugin that – when used right – can fulfill each and every need of a customer. Recently, I had to restrict the payment methods of WooCommerce for specific zipcodes. I could easily use jQuery and hide/show the requested zipcodes but what if the customer wanted to do that himself? ACF comes to the rescue!

  • Create a private wordpress page.
  • Then, create your custom field and assign the display of the field to the private page you created.
  • Navigate to the private page url, hit F12 and check the classes of <body>. Mark the Page-ID somewhere.
E.g. the ID is 8625

Adding Custom Widget to Dashboard

In your functions.php:

<?php // Don't copy opening tag

// Add Zipcode dashboard widget.
function add_custom_dashboard_widget() {
	wp_add_dashboard_widget(
		'zipcode_widget', // Widget ID
		'Restrict Payment Methods', // Title of Widget
		'dashboard_widget_function' // Callback Function
	);
}
add_action( 'wp_dashboard_setup', 'add_custom_dashboard_widget' );

Registering an ACF Form

Don’t forget to replace below info with your own. In your functions.php:

<?php // Don't copy opening tag

// Create ACF Form that holds our Field
add_action('acf/init', 'custom_form');
function custom_form() {

    // Check function exists.
    if( function_exists('acf_register_form') ) {

        // Register form.
        acf_register_form(array(
		'id'       => 'custom_form', // This is the ID of our form
		'post_id'  => '8625', // REPLACE WITH PAGE ID
		'fields' => ['field_612c9ee492047'], // REPLACE WITH ACF FIELD KEY OR ID
		'submit_value' => __('Submit Button Text', 'acf'),
		'updated_message' => __('This is the message you get after updating!', 'acf'),
        ));
    }
}

If you save and check your dashboard, it should display a new widget. However, the widget is empty because the callback function (dashboard_widget_function) is not set. Let’s add it:

Callback Function that links ACF Form to Custom Widget

In your functions.php:

<?php // Don't copy opening tag

// Callback Function of the Custom Dashboard Widget.
function dashboard_widget_function() {
	echo acf_form_head();
	echo acf_form('custom_form'); // The ID of the form we want to display
}

Navigate back to Dashboard and your custom widget should display the custom field that you set. If you change the value and update, the changes will be applied to the corresponding page. You could use that field to multiple pages/posts and by passing just one Page-ID like we did, all of them should get updated – right through the dashboard!