I am using wordpress and need to dynamically populate a dropdpown. How ever I am having issues with fopen php function in wordpress. https://stackoverflow.com/questions/21990467/
So I've given up trying to import csv file and resorted to just placing my csv file contents into an wordpress options field for a quick fix.
But I am struggling with exploding the csv string safely to then use specific columns for choice label and values.
Can any please advise on how I can do this?
Thank you in advance.
The function
// rider nationality
function motocom_rider_nationality( $field )
{
// reset choices
$field['choices'] = array();
// get the textarea value from options page without any formatting
$choices = get_field('nationality_codes', 'option', false);
// explode the value so that each line is a new array piece
$choices = explode(",", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
$field['choices'] = array(
null => 'Select nationality...'
);
// loop through array and add to field 'choices'
if( is_array($choices) )
{
foreach( $choices as $choice )
{
$label = $choice['Country'];
$value = $choice['A4'];
$field['choices'][ $value ] = $label;
}
}
// Important: return the field
return $field;
}
add_filter('acf/load_field/name=rider_nationality', 'motocom_rider_nationality');
The csv string in the options textarea field...
Country,A2,A3,Number
Aaland Islands,AX,ALA,248
Afghanistan,AF,AFG,4
Albania,AL,ALB,8
Algeria,DZ,DZA,12
Samoa,AS,ASM,16
Andorra,AD,AND,20
str_getcsv()
?str_getcsv
(it should be obvious from the output that the newline chars gets included into the output).str_getcsv
works just fine, fix your code. It's also obvious thatstr_getcsv
should be called inside a loop, which does not happen.