API to Posts Plugin – Filter & Action Hooks
These actions and filters help extend or modify the functionality of the API to Posts plugin. Code snippets would need to be added to your themes functions.php file.
Filter: wpgetapi_api_to_posts_mapped_value
This filter allows you to modify any value when importing. Handy for date formatting or translations.
function wpgetapi_modify_a_value( $value ) {
if( $value === 'sold out' ) {
$value = 'Ausverkauft';
}
// looks for date format like 23.09.2023 and changes to 2023-09-23
if( preg_match('/^(\d{2}).(\d{2}).(\d{4})$/', $date) ) {
$DateTime = DateTime::createFromFormat( 'd.m.Y', $value );
$value = $DateTime->format( 'Y-m-d' );
}
return $value;
}
add_filter( 'wpgetapi_api_to_posts_mapped_value', 'wpgetapi_modify_a_value', 10, 1 );
Filter: wpgetapi_api_to_posts_pagination_delay
This filter is only relevant for endpoints that utilise paging. This filter allows you to set a delay between calling each paginated endpoint. The default is set to 0.2 and we have this delay in place to avoid ‘too many requests’ errors.
function wpgetapi_modify_pagination_delay( $value ) {
return 0.4;
}
add_filter( 'wpgetapi_api_to_posts_pagination_delay', 'wpgetapi_modify_pagination_delay', 10, 1 );
Filter: wpgetapi_api_to_posts_importer_items_before_save
This filter allows you to modify your API data before it is saved when running the importer. In the example below, the id of the product was buried within a ‘Product’ sub-array. The example grabs the id from the sub-array and places it on the top level array of the product so that the importer recognises the id.
function wpgetapi_modify_product_id( $items ) {
foreach ($items as $i => $value) {
if( isset( $value['Product']['id'] ) ) {
$items[ $i ]['id'] = $value['Product']['id'];
}
}
return $items;
}
add_filter( 'wpgetapi_api_to_posts_importer_items_before_save', 'wpgetapi_modify_product_id', 10, 1 );
Filter: wpgetapi_api_to_posts_get_item_for_mapping
This filter allows you to modify the id of the item that is used for mapping. The plugin simply looks at the first item (item 0) to create the mapping options and to display the preview data within the Mapping tab. Using this filter you can change which item is used for the mapping. This is useful if item 0 does not contain all of the data required to be mapped.
function wpgetapi_modify_mapping_item( $i ) {
// setting to 1 returns the second item (0 is first item)
return 1;
}
add_filter( 'wpgetapi_api_to_posts_get_item_for_mapping', 'wpgetapi_modify_mapping_item', 10, 1 );