简体   繁体   中英

Adding Parameters to Wordpress PHP Function

Please forgive me if my verbiage is incorrect!

I have a working function that outputs a font-awesome icon based on a post's category. I'm looking to expand the function so I can also specify the size within my call, based on an array within the function.

Here's the working code

<?php echo category_icon(); ?> -- html output is <i class="fa fa-desktop"></i>)  

And I'm looking to achieve the following...

<?php echo category_icon($icon_size); ?>  --output would be <i class="fa fa-desktop$icon_size"></i>)  

And here is my current function

function category_icon($icon_size){
    $build_icon_cat = get_the_category();
    $choose_icon = $build_icon_cat[0]->cat_ID;

            // chooses icon by category
            if ($choose_icon == 19) $build_icon_dos = 'fa fa-desktop';
             elseif ($choose_icon == 15) $build_icon_dos = '<i class="fa fa-cog';

    //-------size array
$icon_size = array(
    '' => '',
    '1' => ' fa-lg',
    '2' => ' fa-2x',
    '3' => ' fa-3x',
    '4' => ' fa-4x',
    '5' => ' fa-5x',
  );

//variables for building
        $build_icon_uno = '<i class="';
        $build_icon_cuatro = '"></i>';
        $display_category_icon = $build_icon_uno . $build_icon_dos . $icon_size . $build_icon_cuatro;

return $display_category_icon;

You have $icon_size set as an argument, and then you're redeclaring it as an array. Change the name of the array to something like $icon_array , and then you can retrieve a size like so: $icon_array[$icon_size] , where $icon_size is simply a matching index (ie: '', '1', '2'...).

You may also want to consider implementing some basic validation using isset , as well as some default sizing.

Thanks to maiorano84 for providing the insight. Here is the working code.

Callback on index.php

<?php echo category_icon('5'); ?>  

Working function

function category_icon($icon_size){
    $build_icon_cat = get_the_category();
    $choose_icon = $build_icon_cat[0]->cat_ID;

            // chooses icon by category
            if ($choose_icon == 19) $build_icon_dos = 'fa fa-desktop';
             elseif ($choose_icon == 15) $build_icon_dos = '<i class="fa fa-cog';

    //-------size array
$icon_array = array(
    '' => '',
    '1' => ' fa-lg',
    '2' => ' fa-2x',
    '3' => ' fa-3x',
    '4' => ' fa-4x',
    '5' => ' fa-5x',
  );

//variables for building
        $build_icon_uno = '<i class="';
        $build_icon_cuatro = '"></i>';
        $display_category_icon = $build_icon_uno . $build_icon_dos . $icon_array[$icon_size] . $build_icon_cuatro;

return $display_category_icon;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM