如何在函数中包装php代码?

时间:2012-07-30 10:10:34

标签: php function

您好我需要将此代码包装在一个函数中以便以后使用它,我是php新手任何帮助请

$term_slug = get_query_var( 'term' );
$taxonomyName = get_query_var( 'taxonomy' );
$current_term = get_term_by( 'slug', $term_slug, $taxonomyName );
$args = array( 'child_of' => $current_term->term_id, 'hide_empty'=>false);
$terms = get_terms( 'tagportifolio', $args);
$assoc = taxonomy_image_plugin_get_associations();

if (!empty($terms)):
?>

<?php foreach( $terms as $child ): ?>
<?php if(array_key_exists( $child->term_taxonomy_id, $assoc )){echo wp_get_attachment_image( $assoc[$child->term_taxonomy_id], array(), false, 'thumbnail'); }
?>
<a href="<?php echo get_term_link( $child->name, $taxonomyName );?>">
<?php echo $child->name; ?></a ><br/>
<?php endforeach; ?>
<?php else: ?>

由于

1 个答案:

答案 0 :(得分:0)

它可能会有所帮助,格式很小,并且如果需要使用变量来返回整个html以使其正常运行,

<?php
function formatOutput()
{
    $term_slug = get_query_var( 'term' );
    $taxonomyName = get_query_var( 'taxonomy' );
    $current_term = get_term_by( 'slug', $term_slug, $taxonomyName );
    $args = array( 'child_of' => $current_term->term_id, 'hide_empty'=>false);
    $terms = get_terms( 'tagportifolio', $args);
    $assoc = taxonomy_image_plugin_get_associations();
    $output = '';
    if (!empty($terms))
    {
        foreach($terms as $child ) 
        {
            if(array_key_exists( $child->term_taxonomy_id, $assoc ))
            {
                $output .= wp_get_attachment_image( $assoc[$child->term_taxonomy_id], array(), false, 'thumbnail'); 
            }
            $output .= "<a href=get_term_link( $child->name, $taxonomyName ) >$child->name;</a >";  
        }
    }
    else
    {
        /* else code  : might be empty output*/
        $output .= '';
    } 
    return $output;
}
 ?>