2012-09-28 74 views
1

我創建了一個函數來獲取我的文章縮略圖和後退圖像。函數將數組傳遞給定義的鍵

<?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 } ?> 

但我相信傳遞數組會比這更好。但我不知道如何創建可以通過預定義鍵傳遞的函數。與$ title_attr分配的數組相同()。或者wordpress $ args如何工作。

回答

4

你也可以試試這個

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'] 
    ... 
} 
+0

奇妙的是我一直在尋找的 –

+0

不客氣:-) –

4

「傳遞一個具有預定義鍵的數組」不是PHP理解的概念。你可以簡單地這樣做雖然:

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']; 
    ... 

此功能接受一個數組,並填充了未使用默認值傳遞的所有鍵。您可以使用它喜歡:

png_thumb(array('thumbsize' => 42, ...)); 
+0

但如何分配這些鍵值,以合適的地方? –

+0

「適當的地方」是什麼意思? – deceze

+0

我的意思是如果我通過密鑰nothumb abnd我想要在一個特定的區域使用該值。我如何分配?我從來沒有使數組的功能如此混亂 –