导航菜单

有人报告插件不能用,Helper::widgetById() 方法报错,看报错是widgetById()里的新建类没有提供足够的参数,但是我来回切1.1和1.2没发现问题,后来对比版本号发现我用的两个都是开发版本,而报告错误的兄弟用的是1.1稳定版,上Typecho的Git Issues里一搜,1.1稳定版的 BUG,狗日了。

因为到目前为止,1.2的稳定版还没正式发布,作为 Typecho 主题/插件作者当然要兼容这两个版本,这里不多说了,直接给出代码吧。

/**
 * 根据ID获取单个Widget对象
 *
 * @param string $table 表名, 支持 contents, comments, metas, users
 * @return Widget_Abstract
 */
function widgetById($table, $pkId)
{
    if (class_exists('\Typecho\Widget')) return Helper::widgetById($table, $pkId);
    $table = ucfirst($table);
    if (!in_array($table, array('Contents', 'Comments', 'Metas', 'Users'))) {
        return NULL;
    }

    $keys = array(
        'Contents'  =>  'cid',
        'Comments'  =>  'coid',
        'Metas'     =>  'mid',
        'Users'     =>  'uid'
    );

    $className = "Widget_Abstract_{$table}";
    $key = $keys[$table];
    $db = Typecho_Db::get();

    $widget = new $className(Typecho_Request::getInstance(), Typecho_Widget_Helper_Empty::getInstance());

    $db->fetchRow(
        $widget->select()->where("{$key} = ?", $pkId)->limit(1),
        array($widget, 'push'));

    return $widget;
}

把上边的代码添加functions.php,然后就可以使用widgetById方法替换原来的Helper::widgetById