1

I have created one function to get my post thumbnail and fall back image.

<?php
function png_thumb($class=null,$thumbsize=null,$no_thumb,$imgclass=null,$extras=null,$hover_content=null){

    $title_attr = array(
        'title' => get_the_title(),
        'alt' => get_the_title(),
        'class' => $imgclass
    );  ?>


    <div class="<?php echo $class ?>">
        <a href="<?php the_permalink(); ?>" title="<?php //the_title(); ?>">
            <?php if ( has_post_thumbnail() ) {
                the_post_thumbnail($thumbsize, $title_attr);
            } else { ?>
                <img src="<?php bloginfo('template_directory'); ?>/images/<?php echo $no_thumb ?>" alt="<?php the_title(); ?>" class="<?php echo $imgclass; ?>" <?php echo $extras; ?> />
            <?php } ?>                          
        </a>
        <?php if($hover_content != "") { ?>
        <a href="<?php the_permalink(); ?>"><div class="hovereffect"><?php echo $hover_content; ?></div></a>
        <?php } ?>
    </div>

<?php } ?>

But I believe passing array would be better than this. But I don't know how can I create such function which can pass with pre-defined key. Same like $title_attr assigned array(). Or how wordpress $args works.

Peon
  • 7,902
  • 7
  • 59
  • 100
Code Lover
  • 8,099
  • 20
  • 84
  • 154

2 Answers2

5

"Passing an array with predefined keys" is not a concept PHP understands. You can simply do this though:

function png_thumb(array $args = array()) {
    $args += array('class' => null, 'thumbsize' => null, 'no_thumb' => null, 'imgclass' => null, 'extras' => null, 'hover_content' => null);

    echo $args['class'];
    ...

This functions accepts an array and populates all keys that were not passed with default values. You use it like:

png_thumb(array('thumbsize' => 42, ...));
deceze
  • 510,633
  • 85
  • 743
  • 889
  • but how to assign those key value to appropriate places? – Code Lover Sep 28 '12 at 06:34
  • What do you mean by "appropriate places"? – deceze Sep 28 '12 at 06:34
  • I mean if i pass key nothumb abnd i want to use that value on one specific area. how can i assign? I never make function with array so confused – Code Lover Sep 28 '12 at 06:42
  • Sheikh Heera's answer work and perfect for my function as it was already in used. However I found your answer is also so useful and appropriate so voting up. Thanks a lot for your help and effort. – Code Lover Sep 28 '12 at 07:23
4

You can also try this

function png_thumb($args=array()) {
    $default= array('class' => null, 'thumbsize' => null, 'no_thumb' => null, 'imgclass' => null, 'extras' => null, 'hover_content' => null);
    $settings=array_merge($default,$args);
    extract($settings); // now you can use variables directly as $class, $thumbsize etc, i.e
    echo $class; // available as variable instead of $settings['class']
    echo $thumbsize; // available as variable instead of $settings['thumbsize']
    ...
}
The Alpha
  • 143,660
  • 29
  • 287
  • 307