【问题标题】:How to wrap php code inside a function? [closed]如何将php代码包装在函数中? [关闭]
【发布时间】:2012-07-30 10:10:34
【问题描述】:

您好,我需要将此代码包装在一个函数中以供以后使用,我是 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: ?>

谢谢

【问题讨论】:

标签: php function


【解决方案1】:

它可能会有所帮助,格式很少,如果需要它可以使用变量返回整个 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;
}
 ?>

【讨论】:

  • 然后我可以使用 echo formatOutput();
  • excatly。希望这可以给你一些提示,进一步你可以为你的函数添加参数并让它变得更好。
  • 更新:当我在我的功能页面中添加您的功能代码时,{ else} 给我语法错误??
  • corrected.extra : 在 else 之后是否存在
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 2019-02-13
  • 2016-05-01
  • 2020-04-04
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多