Php WordPress函数-修复以停止重复代码

Php WordPress函数-修复以停止重复代码,php,wordpress,Php,Wordpress,我正在使用下面的PHP脚本在我的站点的团队区域查找最新的帖子 我还使用一个非常类似的工具在我的主页上查找最新的新闻条目 为了减少重复代码的数量(DRY),有没有一种方法可以让我使用一个函数,只需输入一个特定的自定义帖子类型,例如最新的(“团队”)将显示我的团队的最新帖子 以下是我现有的代码: <?php // find most recent post $new_loop = new WP_Query( array( 'post_type' => 'team'

我正在使用下面的PHP脚本在我的站点的
团队
区域查找最新的帖子

我还使用一个非常类似的工具在我的主页上查找最新的新闻条目

为了减少重复代码的数量(
DRY
),有没有一种方法可以让我使用一个函数,只需输入一个特定的自定义帖子类型,例如
最新的(“团队”)
将显示我的
团队的最新帖子

以下是我现有的代码:

<?php
    // find most recent post
    $new_loop = new WP_Query( array(
    'post_type' => 'team',
        'posts_per_page' => 1,
        "post_status"=>"publish"
    ));
?>

<?php if ( $new_loop->have_posts() ) : ?>
    <?php while ( $new_loop->have_posts() ) : $new_loop->the_post(); ?>

          <h2><?php the_title(); ?></h2>

          <?php the_content(); ?>

    <?php endwhile;?>
<?php else: ?>
<?php endif; ?>
<?php wp_reset_query(); ?>



是的,这确实是可能的

首先你需要做的是

将以下代码添加到主题的
functions.php
文件中:

function most_recent($name){

    // find most recent post
    $new_loop = new WP_Query( array(
                        'post_type' => $name,
                        'posts_per_page' => 1,
                        "post_status"=>"publish"
                ));

    if ( $new_loop->have_posts() ) :
        while ( $new_loop->have_posts() ) : $new_loop->the_post();

          echo "<h2>".the_title()."</h2>";
          the_content();

            endwhile;
    else:
    endif;
    wp_reset_query();
}
因此,在您的情况下,它将是
最新的('team')
,甚至您也可以像我对
产品
所做的那样用于其他产品


如果您有任何疑问,请告诉我。

经过一点努力,效果非常好。现在看起来非常明显:)我把第3行改为
'post_type'=>$type,
Woops,很抱歉!试图同时回答两个问题。这篇文章已被编辑。非常感谢您的回答和详细回复。我发现它非常有用:)很高兴你发现它有用:)编码快乐!
function most_recent($name){

    // find most recent post
    $new_loop = new WP_Query( array(
                        'post_type' => $name,
                        'posts_per_page' => 1,
                        "post_status"=>"publish"
                ));

    if ( $new_loop->have_posts() ) :
        while ( $new_loop->have_posts() ) : $new_loop->the_post();

          echo "<h2>".the_title()."</h2>";
          the_content();

            endwhile;
    else:
    endif;
    wp_reset_query();
}
 $most_recent = most_recent('product');
 echo $most_recent;