Personalizing the Typecho Theme Facile

The blog's previous theme was Initial, which served for two or three years before I moved to Facile, now at version 2.5. So I can keep following the author's updates later, I only changed what my own needs called for.

1. Custom CSS

header .navbar{border-width:0 0 1px 0;}
.post-list .post .post-title{font-size:26px;}
.sidebar section h2{font-size:14px;}
.sidebar section ul li{font-size:14px;}
.sidebar section ul li a{font-size:14px;}
.sidebar .latest-comment .media-body p{font-size:14px;}
.text-color{font-size:14px;word-wrap:break-word;word-break:break-all;}
.post-page article .post-content p{line-height:1.8;}
.post-page article .post-content img:not(.logo){display:inline;}
.post-page article .post-content blockquote{font-size:14px;padding:10px 10px 10px 20px;border-radius:0.5rem;}
.light-color .post-page article .post-content blockquote{border-left:4px solid #ca896d;background:#f3f3f3;color:#444;}
.dark-color .post-page article .post-content blockquote{border-left:4px solid #d69d85;background:#1e1e1e;color:#bbb;}
.archive-title{border-radius:4px;padding:18px 20px 10px;text-align:center;}
.archive-page .archives .archives-item ul li .day{text-align:right;}
.light-color .archive-title{background:#f3f3f3;}
.dark-color .archive-title{background:#16161a;}
.nav-item{font-size:14px;}
.nitxt .form-control{height:calc(2.25em + .75rem + 3px);}
.nitxt .required{color:#f00;}
.text-truncate{font-size:16px;}
.table-responsive{font-size:16px;}
code{font-size:100%;padding:0 4px;}
#comments .comment-input .row div{margin-bottom:0;}
#comments .comment-input .row div.nitxt{margin-bottom:16px;}
#comments .comments-lists .comment-author .comment-reply a, #comments .comments-lists .comment-author .comment-reply i{font-size:12px;color:#888;}
#copyright-info p{font-size:.8125rem;line-height:120%;}
#copyright-info p a{font-size:.8125rem;}
footer .text-center {font-size:12px;}
@media screen and (max-width:575px) {
  .post-list .post .post-title{font-size:22px;}
  .post-page .post-title{font-size:24px;}
}
@media (prefers-color-scheme: dark) {
  .archive-title{background:#16161a;}
  .post-page article .post-content blockquote{border-left:4px solid #d69d85;background:#1e1e1e;color:#bbb;}
}
@media (prefers-color-scheme: light) {
  .archive-title{background:#f3f3f3;}
  .post-page article .post-content blockquote{border-left:4px solid #ca896d;background:#f3f3f3;color:#444;}
}
Note: in comment-input.php, add nitxt to the class of the div wrapping input and textarea, so the input field and the Captcha box line up to the same height.

2. Custom JS That Drops target="_blank" from Internal Links

<script>
document.addEventListener('DOMContentLoaded',function(){
const h=window.location.hostname,l=document.querySelectorAll('.post-content a');
l.forEach(i=>{const r=i.getAttribute('href');r&&(!r.startsWith('http')||r.includes(h))&&(i.target='_self',i.removeAttribute('target'))});
});
</script>

Note: the author's template already applies target="_blank" globally in its JS.

3. A Dash Between the Site Title and Tagline

Find <?php if ($this->is('index')) echo $this->options->tagline; ?> in header.php and change it to: <?php if ($this->is('index')) echo ' - ' . $this->options->tagline; ?>

4. Add Post Categories to the Navigation

Find <?php $this->widget('Widget_Contents_Page_List')->to($pages); ?> in header.php and add this above it:

<?php $this->widget('Widget_Metas_Category_List@nav')->to($category); ?>
<?php while($category->next()): ?>
<li class="nav-item<?php if ($this->is('category', $category->slug)) echo ' active'; ?>">
  <a class="nav-link" href="<?php $category->permalink(); ?>"<?php if ($this->is('category', $category->slug)) echo ' aria-current="category"'; ?>><?php $category->name(); ?></a>
</li>
<?php endwhile; ?>

5. Show a Thumbnail and Summary When a Post Is Shared

Find <link rel="icon" href="<?php echo $this->options->logoUrl?$this->options->logoUrl:$this->options->siteUrl . 'favicon.ico'; ?>" type="image/x-icon"> in header.php and add this above it:

<?php if ($this->is('post') || $this->is('page')): ?>
<?php
// Grab the thumbnail
$thumb = '';
// Try the custom field first
if ($this->fields->thumb) {
    $thumb = $this->fields->thumb;
} 
// Otherwise, pull the first image out of the content
else {
    preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $this->content, $matches);
    if (!empty($matches[1])) {
        $thumb = $matches[1];
    }
}
// Normalize the image path into a full URL
if (!empty($thumb)) {
    // Already a full URL (http/https or //)? Leave it as is
    if (!preg_match('/^(https?:)?\/\//i', $thumb)) {
        // Not a full URL -- prepend the site root URL
        if (strpos($thumb, '/') === 0) {
            // Starts with a slash, so it's an absolute path under the site root
            $thumb = rtrim($this->options->siteUrl, '/') . $thumb;
        } else {
            // Relative path: build it on the site root URL
            $thumb = rtrim($this->options->siteUrl, '/') . '/' . ltrim($thumb, '/');
        }
    }
} 
// No image? Fall back to the default
else {
    $thumb = rtrim($this->options->siteUrl, '/') . '/usr/themes/' . $this->options->theme . '/images/default.png';
}
// Build the description
if ($this->fields->excerpt) {
    $description = $this->fields->excerpt;
} elseif ($this->description) {
    $description = $this->description;
} else {
    $description = Typecho_Common::subStr(strip_tags($this->excerpt), 0, 150, '...');
}
?>
    <meta property="og:title" content="<?php $this->title() ?>" />
    <meta property="og:type" content="article" />
    <meta property="og:url" content="<?php $this->permalink() ?>" />
    <meta property="og:image" content="<?php echo $thumb ?>" />
    <meta property="og:image:width" content="800" />
    <meta property="og:image:height" content="800" />
    <meta property="og:description" content="<?php echo htmlspecialchars($description) ?>" />
    <meta property="og:site_name" content="<?php $this->options->title() ?>" />
    <!-- Twitter -->
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="<?php $this->title() ?>" />
    <meta name="twitter:description" content="<?php echo htmlspecialchars($description) ?>" />
    <meta name="twitter:image" content="<?php echo $thumb ?>" />
    <!-- Wechat -->
    <meta property="wechat:article:title" content="<?php $this->title() ?>" />
    <meta property="wechat:article:description" content="<?php echo htmlspecialchars(Typecho_Common::subStr(strip_tags($description), 0, 120, '...')) ?>" />
    <meta property="wechat:article:image" content="<?php echo $thumb ?>" />
<?php endif; ?>

6. Suppress the Extra <head> Meta Tags

Find <?php $this->header(); ?> in header.php and change it to: <?php $this->header('generator=&template=&pingback=&xmlrpc=&wlw=&rss1=&rss2=&atom=&social='); ?>

Note: social was added in Typecho 1.3.0.

7. Random Posts in the Sidebar

At the very bottom of helpers.php, add:

function getRandomPosts($random = 5) {
    $db = Typecho_Db::get();
    $adapterName = $db->getAdapterName(); // Handles non-MySQL databases too
    if ($adapterName == 'pgsql' || $adapterName == 'Pdo_Pgsql' || $adapterName == 'Pdo_SQLite' || $adapterName == 'SQLite') {
        $order_by = 'RANDOM()';
    } else {
        $order_by = 'RAND()';
    }
    
    $sql = $db->select()->from('table.contents')
        ->where('status = ?', 'publish')
        ->where('table.contents.created <= ?', time())
        ->where('type = ?', 'post')
        ->limit($random)
        ->order($order_by);

    $result = $db->fetchAll($sql);
    if ($result) {
        foreach ($result as $val) {
            // Instantiate the content widget and push the row into it
            $obj = Typecho_Widget::widget('Widget_Abstract_Contents');
            $obj->push($val);
            
            // Read values through object properties so missing array keys don't break it
            $post_title = htmlspecialchars($obj->title);
            $permalink = $obj->permalink;
            
            echo '
                <li>
                    <a href="' . $permalink . '" title="' . $post_title . '">' . $post_title . '</a>
                </li>';
        }
    }
}

Then add the matching code in sidebar.php:

        <?php if ($component == 'Recommend Posts'): ?>
            <!-- Latest posts -->
            <section class="ml-xl-4 ml-lg-3 mb-5">
                <h2 class="mb-4"><?php echo $GLOBALS['t']['sidebar']['recommendPosts']; ?></h2>
                <ul aria-label="<?php echo $GLOBALS['t']['sidebar']['recommendPosts']; ?>">
<?php getRandomPosts(10);?>
                </ul>
            </section>
        <?php endif; ?>

In the language pack, under 'sidebar' => array(, add: 'recommendPosts' => 'Recommend Posts',. The English language pack needs the same entry. Finally, under Appearance → Theme Settings → Sidebar Widgets, add Recommend Posts.

8. Add rel="nofollow" to Outbound Links in Post Content

Find this line in post.php:

$GLOBALS['post']['content'] = addBootstrapTableClasses($GLOBALS['post']['content']);

and add the code below right after it:

// ========== Core feature: automatically add rel="nofollow" to outbound links (wildcard-domain aware) ==========
function autoAddNofollowToExternalLinks($content, $siteUrl) {
    // 1. Parse and normalize this site's root domain (pull out yourname.site; covers every subdomain)
    $siteParsed = parse_url(rtrim($siteUrl, '/'));
    $siteHost = isset($siteParsed['host']) ? strtolower($siteParsed['host']) : '';
    if (empty($siteHost)) return $content;

    // Pull out the root domain
    $siteHostParts = explode('.', $siteHost);
    $rootDomain = count($siteHostParts) >= 2 
        ? $siteHostParts[count($siteHostParts)-2] . '.' . $siteHostParts[count($siteHostParts)-1] 
        : $siteHost; // Fallback in case the domain is oddly formatted

    // 2. Match every <a> tag, capturing href and all other attributes
    $pattern = '/<a\s+([^>]*?)href=["\']([^"\']+)["\']([^>]*?)>/i';
    $content = preg_replace_callback($pattern, function($matches) use ($rootDomain) {
        $fullTag = $matches[0];
        $preHrefAttr = trim($matches[1]); // attributes before href
        $href = $matches[2];               // the link address
        $postHrefAttr = trim($matches[3]); // attributes after href
        $allAttrs = $preHrefAttr . ' ' . $postHrefAttr; // join all attributes, collapsing whitespace
        $allAttrs = preg_replace('/\s+/', ' ', $allAttrs);

        // 3. Decide whether it's an internal link (the key part: wildcard match on *.yourname.site)
        $isInternal = false;
        $hrefTrim = rtrim($href, '/');
        
        // Case 1: relative path with no domain (e.g. /post/123, about.html)
        if (strpos($href, '://') === false && !preg_match('/^\/\/[^\/]+/', $href)) {
            $isInternal = true;
        }
        // Case 2: absolute URL containing the *.yourname.site domain
        else {
            $hrefParsed = parse_url($hrefTrim);
            $hrefHost = isset($hrefParsed['host']) ? strtolower($hrefParsed['host']) : '';
            if (!empty($hrefHost)) {
                // Matching rules:
                // 1. Exact match on the root domain (yourname.site)
                // 2. Match any subdomain (*.yourname.site)
                if ($hrefHost === $rootDomain || substr($hrefHost, -strlen($rootDomain) - 1) === '.' . $rootDomain) {
                    $isInternal = true;
                }
            }
        }

        // 4. Internal link: return the tag untouched
        if ($isInternal) {
            return $fullTag;
        }

        // 5. Outbound link: skip if it already carries rel="nofollow"
        if (preg_match('/rel\s*=\s*["\'](.*?)nofollow(.*?)["\']/i', $allAttrs)) {
            return $fullTag;
        }

        // 6. Outbound link without nofollow: add or append rel="nofollow"
        if (preg_match('/rel\s*=\s*["\'][^"\']+["\']/i', $allAttrs)) {
            // rel already there, so append (rel="noopener" becomes rel="noopener nofollow")
            $allAttrs = preg_replace('/rel\s*=\s*["\']([^"\']+)["\']/i', 'rel="$1 nofollow"', $allAttrs);
        } else {
            // no rel attribute, so add rel="nofollow"
            $allAttrs .= ' rel="nofollow"';
        }

        // 7. Reassemble the <a> tag (same attribute order, rel is the only change)
        return '<a ' . trim($allAttrs) . ' href="' . $href . '">';
    }, $content);

    return $content;
}

// Run the outbound-link pass, passing in this site's domain
$GLOBALS['post']['content'] = autoAddNofollowToExternalLinks(
    $GLOBALS['post']['content'],
    $this->options->siteUrl
);
// ========== End of outbound-link handling ==========

Leave a Comment

Comments No Comments

Table of Contents