Documentation / Code Snippets

Add fields to ImportWP Pro Custom field dropdown list

The following code demonstrates how to register your own custom fields and display them in the custom field dropdown when using ImportWP PRO, allowing you to display different custom fields for all import templates such as posts, pages, custom post types, taxonomies and users.

<?php
use ImportWP\Common\Model\ImporterModel;
use ImportWP\EventHandler;

/**
 * Add fields to custom field dropdown list
 * 
 * @param array $fields Current list of custom fields ```['value' => '', 'label' => '']```
 * @param ImporterModel $importer_model 
 * @return array List of fields formatted ```['value' => '', 'label' => '']```
 */
function iwpcf_get_custom_fields($fields, ImporterModel $importer_model)
{
    $custom_fields = [
        ['value' => '_test_01', 'label' => 'Custom Field 01'],
        ['value' => '_test_02', 'label' => 'Custom Field 02']
    ];

    $template = $importer_model->getTemplate();
    switch ($template) {
        case 'user':
            $fields = array_merge($fields, $custom_fields);
            break;
        case 'term':
            $taxonomy = $importer_model->getSetting('taxonomy');
            $fields = array_merge($fields, $custom_fields);
            break;
        default:
            $post_type = $importer_model->getSetting('post_type');
            $fields = array_merge($fields, $custom_fields);
            break;
    }
    return $fields;
}

/**
 * Hook into ImportWP Pro Event handler to modify custom field list
 *
 * @param EventHandler $event_handler
 * @return void
 */
function iwpcf_register_event_handler(EventHandler $event_handler)
{
    $event_handler->listen('importer.custom_fields.get_fields', 'iwpcf_get_custom_fields');
}
add_action('iwp/register_events', 'iwpcf_register_event_handler');