【问题标题】:Home Template Loop customization - should fetch content based on post template主页模板循环自定义 - 应根据帖子模板获取内容
【发布时间】:2019-07-16 15:28:56
【问题描述】:

在主题中有两个文件:

  1. single.php

  2. f-template.php → 用于默认帖子类型。它有不同的设计。

Home.php 将获取前 10 个帖子,它们可以在上述任何模板中。

但是,需要的是 home.php 上的内容来自f-template.php

那么这两个东西应该在home.php上实现

function folder_paragrapgh($content){
        return preg_replace('/<p([^>]+)?>/', '<p class="para para2">', $content);
        }
        add_filter('the_content', 'folder_paragrapgh');

<script>
    (function($) {
        // do all your $ based jquery in here.
        $(function() {
          $('p.class2').prepend('<img src="http:/sample.com/img/folder.svg" width="50" height="25" alt="">');
        });
    })(jQuery);
</script>

我试过这个:

if( is_page_template( 'f-template.php' ) ) {

    function folder_paragrapgh($content){
        return preg_replace('/<p([^>]+)?>/', '<p class="para para2">', $content);
        }
        add_filter('the_content', 'folder_paragrapgh');
    }

    the_content();
}

但这没有用。实际上它是有缺陷的,因为我们正在处理的模板是home.php

那么我们有任何解决方案来实现我们想要实现的目标吗?

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    如果我错了,请纠正我,但听起来您想显示一个带有帖子的循环,其中一些帖子具有不同的设计,具体取决于您为其选择的页面模板。

    您可以通过get_page_template_slug() function 查看正在使用的模板。在循环中使用它以及帖子的 ID。

    // checks if there are any posts that match the query
    if (have_posts()) :
    
        // If there are posts matching the query then start the loop
        while ( have_posts() ) : the_post();
    
            // Assign postId from within the loop
            $postId = the_ID();
    
            if( get_page_template_slug($postId) === 'f-template' ) {
                // Display what you want to see when f-template is selected.
    
            } else {
                // Display what you want to see by default if no condition is met.
    
            }
    
        // Stop the loop when all posts are displayed
        endwhile;
    
    // If no posts were found
    else :
    
        echo '<p>Sorry no posts matched your criteria.</p>';
    
    endif;
    

    is_page_template() function 不起作用,因为它将检查主查询中当前页面的页面模板是什么。

    这完全取决于您的用例,但我个人会使用高级自定义字段添加一个额外的字段来实现此效果。

    祝你好运!

    【讨论】:

    • 您对问题的理解是正确的。你能用它的用法写一个完整的解决方案吗 → get_page_template_slug(
    • 我们可以在没有自定义字段的情况下以某种方式修复它吗?只是让home.php 更聪明?
    • 我添加了一个代码示例,您可以在循环中使用。将 $postId 替换为您正在使用的变量。只需放入 $post 对象也应该可以。
    • 什么是 $postId?某个特定帖子的ID?因为来自该模板的帖子可能很多,我们不能只放一个 ID。我是初学者请多多包涵。
    • 不用担心。我的意思是,当您使用 WordPress 循环时,您可以访问一个名为 the_ID() 的函数。您可以将其值放入变量中,然后使用该变量检查 get_page_template_slug 函数使用的模板。我更新了代码以明确它在循环内使用。进一步明确这一点。循环针对传入的每个帖子运行。因此,对于每个帖子,$postID 变量都将被更改和使用。
    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    相关资源
    最近更新 更多