0
分享

使用自定义字段无插件实现typecho文章置顶功能

浏览 59 去评论

添加文章置顶选项

functions.php 添加以下代码,实现文章撰写和编辑页面右侧添加置顶选项确认按钮。该按钮使用文章自定义字段,确认置顶后,会在文章编辑框下面自动添加自定义字段,所以需要通过 javascript 同步操作。

function oxcat_addStickyCheckbox() {
    $post = Typecho_Widget::widget('Widget_Contents_Post_Edit');
    $isChecked = ($post->fields->isSticky == 1) ? 'checked' : '';
    $html = '<section class="typecho-post-option"><label class="typecho-label">文章置顶</label><p><input type="checkbox" id="is_sticky" name="fields[isSticky]" value="1" ' . $isChecked .'> <label for="is_sticky">首页置顶文章</label></p></section>';
    $html .= '<script>
    document.addEventListener("DOMContentLoaded", function() { 
        var checkbox = document.getElementById("is_sticky"); 
        var isStickyCustom = document.getElementById("fieldvalue");
        checkbox.addEventListener("change", function() {
            if (this.checked) { 
                isStickyCustom.value = "1"; 
            } else { 
                isStickyCustom.value = "0"; 
            } 
        });
    });
    </script>';
    echo $html;
}
Typecho_Plugin::factory('admin/write-post.php')->option = 'oxcat_addStickyCheckbox';

获取所有置顶文章 ID

functions.php 文件中添加下面代码,以获取所有置顶文章 ID,以备后面列表置顶时使用。

function oxcat_getStickyPostIds() {
    $db = Typecho_Db::get();
    $query = $db->select('cid')
        ->from('table.fields')
        ->where('name = ?', 'isSticky')
        ->where('str_value = ?', '1');

    return $db->fetchAll($query, function($row) {
        return (int)$row['cid']; 
    });
}

文章置顶显示

列表功能页面 index.phparchive.php 页面循环部分代码改成下面的代码实现文章置顶显示,为了代码好看引入了 post-item.php 文件。

    // 获取所有置顶文章的 CID
    $stickyIds = oxcat_getStickyPostIds();
    $stickyPosts = [];
    $normalPosts = [];

    // 遍历文章,将置顶文章和普通文章分开
    while ($this->next()) {
        if (in_array($this->cid, $stickyIds)) {
            $stickyPosts[] = clone $this; // 置顶文章
        } else {
            $normalPosts[] = clone $this; // 普通文章
        }
    }

    // 优先显示置顶文章
    foreach ($stickyPosts as $post) {
        $post->need('post-item.php'); 
    }

    // 显示普通文章
    foreach ($normalPosts as $post) {
        $post->need('post-item.php'); 
    }

post-item.php 文件代码示例:

<div class="post">
    <h3 class="post-title">
        <a href="<?php $this->permalink(); ?>" title="<?php $this->title(); ?>">
            <?php $this->title(); ?>
        </a>
        <?php if (in_array($this->cid, oxcat_getStickyPostIds())): ?>
            <span class="red">置顶</span>
        <?php endif; ?>
    </h3>
    <div class="post-summary">
        <?php $this->excerpt(300, "..."); ?>
    </div>
    <div class="post-meta">
        <time datetime="<?php $this->date('c'); ?>" itemprop="datePublished"><?php $this->date(); ?></time>
        <?php $this->category(" | ", true, "默认"); ?>
        <a itemprop="discussionUrl" href="<?php $this->permalink() ?>#comments">
           <?php $this->commentsNum('评论 0', '评论 1', '评论 %d'); ?>
        </a>
    </div>
</div>

评论

还没有评论,快来抢沙发吧!