草庐IT

php - 在页面模板中时不显示自定义 Wordpress 循环

coder 2023-12-30 原文

我的索引文件中有一个自定义的 Wordpress 循环,目前无法正常工作。此自定义 WP 循环的目的是根据其帖子编号分配不同的类和结构。

下面的代码在 index.php 文件中完美运行但是不幸的是,当将其复制到自定义页面模板时它不起作用。

<?php
/**
* Template Name: custom page template
*/
get_header(); ?>

<?php if (have_posts()) : ?>
<?php $count = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?>
<?php if ($count == 1) : ?>

<div class="item1">
<span>hello!</span<?php the_title(); ?>>
</div><!-- .item# --> 

<?php elseif ($count == 2) : ?>      

<div class="item2">
<?php the_title(); ?><span>Hi!</span
</div><!-- .item# --> 

<?php elseif ($count == 3) : ?>      

<div class="item3">
<!-- Put Your Stuff Here -->
</div><!-- .item# --> 

<?php elseif ($count == 4) : ?>      

<div class="item4">
<!-- Put Your Stuff Here -->
</div><!-- .item# --> 

<?php elseif ($count == 5) : ?>      

<div class="item5">
<!-- Put Your Stuff Here -->
</div><!-- .item# -->

<?php else : ?>

<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>

目标:

我想要实现的是创建一个自定义页面(比方说)www.mywebsite.com/my-custom-page,其中列出了所有文章。

如上所述,自定义循环不显示在页面中以及编号的分页中。好像页面模板无法识别或忽略自定义循环代码。

我试过使用 WP Query但仍然没有运气。下面的代码返回“抱歉,没有符合您条件的帖子。”

部分工作的 WP 查询代码

这是我的 website此代码将出现在何处但似乎不起作用

<?php
/**
* Template Name: Custom Page - Blog
*/
get_header(); ?>


<!-- START of WP Query -->

<?php $the_query = new WP_Query( array("post_type"=>'post')); ?>

<?php if ( $the_query->have_posts() ) : ?>

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

<?php $count++; ?>

    <?php if ($count == 1) : ?>
    <div class="item1">
        <span>Post 1</span><?php the_title(); ?>
    </div><!-- .item# --> 

    <?php elseif ($count == 2) : ?>      
    <div class="item2">
    <span>Post 2</span><?php the_title(); ?>
    </div><!-- .item# --> 

    <?php elseif ($count == 3) : ?>      
    <div class="item3">
        <span>Post 3</span><?php the_title(); ?>
    </div><!-- .item# --> 

    <?php elseif ($count == 4) : ?>      
    <div class="item4">
        <span>Post 4</span><?php the_title(); ?>
    </div><!-- .item# --> 

    <?php elseif ($count == 5) : ?>      
    <div class="item5">
        <span>Post 5</span><?php the_title(); ?>
    </div><!-- .item# -->

    <?php elseif ($count >= 5 || $count <= 7) : ?>      
    <div class="item6">
        <span>Post 6 to 7</span><?php the_title(); ?>
    </div><!-- .item# -->

    <?php elseif ($count >= 8 || $count <= 15) : ?>      
    <div class="item6">
        <span>Post 8 onwards - </span><?php the_title(); ?><?php the_excerpt(); ?>
    </div><!-- .item# -->

    <?php elseif ($count >= 16) : ?>      
    <div class="item6">
        <span>Post 8 onwards - </span><?php the_title(); ?><?php the_excerpt(); ?>
    </div><!-- .item# -->
    <?php
    global $wp_query;

        $big = 999999999; // need an unlikely integer

        echo paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $wp_query->max_num_pages
        ) );
    ?>


<?php else : ?>

<?php endif; ?>
<?php endwhile; ?>
<?php else : ?>
<p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

<!-- END of WP Query -->


<?php get_footer(); ?>

    </article>

<?php get_footer(); ?>

感谢您对此的帮助。谢谢!

最佳答案

正如前面的答案所指出的,您可以使用 WP_Query 对帖子、自定义帖子类型 (CPT) 和页面进行自定义查询:

$the_query = new WP_Query( array(
    'post_type'      => 'post',
    'posts_per_page' => 10,
    // other args here
) );

并使用 The Loop显示帖子:

if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        //
        // Post Content here
        //
    } // end while
} // end if

现在提到这个:

Partially Working WP Query Code

Here's my website where this code will appear but seems the not working

我想你的意思是,“分页 不起作用”,对吧?因为它不是:

  1. 因为您使用的是全局 $wp_query反对您的分页。

  2. 在你的WP_Query构造,你没有设置 paged分页正常工作所需的参数。

所以它应该是这样的:

$current_page = max( 1, get_query_var( 'paged' ) ); // the current page
$the_query = new WP_Query( array(
    'post_type'      => 'post',
    'posts_per_page' => 10,
    'paged'          => $current_page,
    // other args here
) );

然后使用$current_page paginate_links() — 你也可以在这里看到,我用了$the_query而不是 $wp_query检索/指定最大页数时:

echo paginate_links( array(
    'current'  => $current_page,
    'total'    => $the_query->max_num_pages, // here I don't use $wp_query
    // other args here
) );

下面是您可以用来代替部分工作代码的工作代码(<!-- START of WP Query --><!-- END of WP Query --> 之间的代码):

<?php
$current_page = max( 1, get_query_var( 'paged' ) );
$the_query = new WP_Query( array(
    'post_type'      => 'post',
    'posts_per_page' => 10,
    'paged'          => $current_page,
    // other args here
) );

if ( $the_query->have_posts() ) :
    $count = 1;
    while ( $the_query->have_posts() ) : $the_query->the_post();
        if ( 1 === $count ) :
        ?>
        <div class="item item1" style="background: red; color: #fff;">
            <span>Post 1</span> <?php the_title( '<h3>', '</h3>' ); ?>
        </div>
        <?php
        elseif ( 2 === $count ) :
        ?>
        <div class="item item2" style="background: orange; color: #fff;">
            <span>Post 2</span> <?php the_title( '<h3>', '</h3>' ); ?>
        </div>
        <?php
        // other conditions here
        else :
        ?>
        <div class="item item3" style="background: yellow; color: #666;">
            <span>Post <?php echo $count; ?></span>
            <?php the_title( '<h3>', '</h3>' ); ?>
        </div>
        <?php
        endif;
        $count++;
    endwhile;
?>
<p>Pagination:</p>
<?php
    $big = 999999999; // need an unlikely integer
    echo paginate_links( array(
        'base'     => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format'   => '?paged=%#%',
        'current'  => $current_page,
        'total'    => $the_query->max_num_pages,
        'type'     => 'list',
        'end_size' => 3,
    ) );
?>
<?php else : ?>
    <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif;

wp_reset_postdata();
?>

关于php - 在页面模板中时不显示自定义 Wordpress 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54997506/

有关php - 在页面模板中时不显示自定义 Wordpress 循环的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  5. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  6. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  7. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  8. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  9. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  10. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

随机推荐