个性化阅读
专注于IT技术分析

我想在WordPress主题的评论部分之前加载”赞助文章链接”

点击下载

我只是从Blogger迁移到Wordpress, 完全迁移成功。

我唯一的问题是, WordPress不允许你直接编辑完整的html代码, 而必须编辑php文件。

我已将我的赞助链接片段添加到Single Post.php下方的

<?php the_content(); ?>

但是我想在代码段之后加载评论, 所以我应该将代码段放在哪里?和什么是正确的方式来做到这一点的PHP?

这是代码:

<?php get_header(); ?>
<div class="mh-wrapper clearfix">
    <div id="main-content" class="mh-content" role="main" itemprop="mainContentOfPage"><?php
        while (have_posts()) : the_post();
            mh_before_post_content();
            get_template_part('content', 'single');
    mh_after_post_content();
        comments_template();

        endwhile; ?>

<div id="sponsored-widget"></div>

<script //soponsored link snippet 
</script>

    </div>
    <?php get_sidebar(); ?>
</div>
<?php get_footer(); ?>

#1


有两种方法:

方法1:直接编辑

<?php ... mh_after_post_content(); ?>
    // Your Custom Codes
<?php comments_template();

方法2:使用WordPress挂钩

在你的functions.php中, 添加以下代码:

add_filter('the_content', 'my_sponsored_widget', 10);
function my_sponsored_widget($content) {
    $sponsored_content = '<div id="sponsored-widget">Sponsored Content</div>';
    return $content . $sponsored_content;
}

在你的情况下, 主题实现了两个动作函数mh_before_post_content()和mh_before_post_content(), 它们用于将自定义内容插入到发布内容之前/之后。我不知道动作挂钩的名称, 但我想它应该与函数名称相同。如果是的话, 你可以像这样添加你的内容:

add_action('mh_before_post_content', 'my_sponsored_widget', 10);
function my_sponsored_widget() {
    echo '<div id="sponsored-widget">Sponsored Content</div>';
}

通常, 除非你是主题开发人员, 否则直接编辑主题文件以自定义主题不是一个好习惯。对于主题用户, 你应该使用WordPress钩子函数add_filter()或add_action()更改/插入某些内容或搜索并使用你需要的某些WordPress插件套件, 在这种情况下, 有很多WP插件可以做你想做的事情, 我刚刚在Google上搜索了两个:简单的自定义内容或在内容后添加小部件。

为什么不应该直接编辑主题?由于主题将来可能会更新, 因此你将需要在每次更新时修改/合并自定义代码。

相关链接

  • //codex.wordpress.org/Plugin_API/Hooks
  • //developer.wordpress.org/reference/functions/add_filter/
  • //developer.wordpress.org/reference/functions/add_action/

附言我也是Stackoverflow的新手, 所以我只能在答案中包含两个链接:)

赞(0)
未经允许不得转载:srcmini » 我想在WordPress主题的评论部分之前加载”赞助文章链接”

评论 抢沙发

评论前必须登录!