0

Suppose I have a function that needs to be able to load a file depending upon an attribute in a shortcode:

[open_file ex1]

How would I go about defining which file name is set as $csv depending upon the attribute given in the shortcode?

This code below doesn't function, but does illustrate what I'm trying to do.

function open_file($atts) {

    if ($atts = "ex1") {
        $csv = "ex1.csv"

    } elseif ($atts = "ex2") {
        $csv = "ex2.csv"

    } elseif ($atts = "ex3") {
        $csv = "ex3.csv"

1 Answer 1

1

It seems that you might have a lot of these .csv files. I would suggest to use only one attribute and then passing the appropriate name to that attribute or the prefix of the file name and then building the file name from there.

You can try one of the following (I have not done any verification, you will propbably check that the attribute is not empty and that the file exists before returning anything in the shortcode)

OPTION 1

Passing the complete file name (my personal choice)

add_shortcode( 'open_file', 'custom_file' );
function custom_file( $atts )
{
    $attributes = shortcode_atts( array(
        'file' => '',
    ), $atts );

    return $attributes['file'];
}

Use it then as follow

[open_file file='ex1.csv']

OPTION 2

Passing the prefix to the attribute

add_shortcode( 'open_file', 'custom_file' );
function custom_file( $atts )
{
    $attributes = shortcode_atts( array(
        'file' => '',
    ), $atts );

    $filename = $attributes['file'] . '.csv';
    return $filename;
}

Use it then as follow

[open_file file='ex1']

By doing it with either of the above methods will eliminate a very long and unnecessary if/else statement

1
  • Any feedback on this. If my answer sopved your issue, please accept my answer by clicking on the checkmark next to it, else, feel free to post your own solution and accept that as the appropriate answer. Don't let your questions go unsolved :-) Commented Apr 6, 2015 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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