在函数中包装代码会阻止它工作

时间:2012-02-14 16:55:11

标签: function wordpress-theming wordpress

我想将我的代码包装在一个函数中(然后将它放在functions.php中),以便我可以在别处调用它,但是当我将它包装在函数中时,我的代码就会失败。

我认为这可能是一个范围问题,我是否必须以某种方式将帖子号传递给函数?如果我摆脱了查询所包含的功能,代码就可以正常工作。

我猜这段代码确实无关紧要(虽然我可能错了) - 它更多地与它是一个循环和一个函数这一事实有关。

        <?php function getGallery2() { ?>
            <!-- 1. search for any pages with a custom field of 'test' that have a value of 'yes' -->
            <?php query_posts('meta_key=Gallery - Promotion Gallery Photo Link&post_type=page'); ?>

            <?php while ( have_posts() ) : the_post(); ?>
                <!-- 2. echo the test field -->
                <?php $link =  get_post_meta($post->ID, 'Gallery - Promotion Gallery Photo Link', true); ?>
                <?php $alt =  get_post_meta($post->ID, 'Gallery - Promotion Gallery Photo Alt text', true); ?>
                <img src="<?php echo $link ?>" alt="<?php echo $alt ?>" />
            <?php endwhile;?>

            <?php wp_reset_query(); ?>

        <?php } ?>

        <?php getGallery2(); ?>

2 个答案:

答案 0 :(得分:1)

我认为你会有这样的事情(未经测试):

<?php function getGallery2() { ?>
    $global post;       
    $link =  get_post_meta($post->ID, 'Gallery - Promotion Gallery Photo Link', true); ?>
    $alt =  get_post_meta($post->ID, 'Gallery - Promotion Gallery Photo Alt text', true); ?>
            <img src="<?php echo $link ?>" alt="<?php echo $alt ?>" />
<?php } ?>

然后在任何PHP页面上的任何循环内调用该函数。合理?即不要在函数内循环。我不明白为什么你不只是使用PHP包括?即

require('get-gallery.php');

希望有所帮助:D

答案 1 :(得分:0)

$ post不在函数范围内。

您可以将global $post;添加到该功能的顶部,也可以将其包含为如下参数:

function getGallery2($post){
    // code
}

echo getGallery2($post)

函数内的代码只能看到在同一函数或全局范围内创建的变量。意味着$post对象未定义。

// 稍微偏离主题说明,PHP中有很多HTML注释。你可以通过将它全部变成PHP来轻松整理事物。

编辑:

function getGallery2(){

    global $post;

    // 1. search for any pages with a custom field of 'test' that have a value of 'yes' -->
    query_posts('meta_key=Gallery - Promotion Gallery Photo Link&post_type=page'); 

    while ( have_posts() ) : the_post(); 
        // 2. echo the test field -->
        $link =  get_post_meta($post->ID, 'Gallery - Promotion Gallery Photo Link', true); 
        $alt =  get_post_meta($post->ID, 'Gallery - Promotion Gallery Photo Alt text', true); 
        echo '<img src="'.$link.'" alt="echo $alt " />';
    endwhile;

    wp_reset_query(); 

} 

getGallery2();