进阶 yourls.org 2026-11-19 17:39:56 · 1 阅读

第6章 YOURLS 插件开发实战:创建 URL 预览功能

示例插件:预览 URL

在短链接后添加“~”字符,可在重定向前显示预览页面

安装

  1. 在 /user/plugins 目录下,新建一个名为 preview-urls 的文件夹
  2. 在此新目录中,创建一个名为 plugin.php 的空文件
  3. 在此新文件中,复制并粘贴以下代码
  4. 前往“插件”管理页面并激活该插件

代码

<?php
/*
Plugin Name: Preview URL
Plugin URI: https://yourls.org/
Description: Preview URLs before you're redirected there
Version: 1.0
Author: Ozh
Author URI: https://ozh.org/
*/

// EDIT THIS

// Character to add to a short URL to trigger the preview interruption
define( 'OZH_PREVIEW_CHAR', '~' );

// DO NO EDIT FURTHER

// Handle failed loader request and check if there's a ~
yourls_add_action( 'loader_failed', 'ozh_preview_loader_failed' );
function ozh_preview_loader_failed( $args ) {
$request = $args[0];
$pattern = yourls_make_regexp_pattern( yourls_get_shorturl_charset() );
if( preg_match( "@^([$pattern]+)".OZH_PREVIEW_CHAR."$@", $request, $matches ) ) {
$keyword = isset( $matches[1] ) ? $matches[1] : '';
$keyword = yourls_sanitize_keyword( $keyword );
ozh_preview_show( $keyword );
die();
}
}

// Show the preview screen for a short URL
function ozh_preview_show( $keyword ) {
require_once( YOURLS_INC.'/functions-html.php' );

yourls_html_head( 'preview', 'Short URL preview' );
yourls_html_logo();

$title = yourls_get_keyword_title( $keyword );
$url = yourls_get_keyword_longurl( $keyword );
$base = YOURLS_SITE;
$char = OZH_PREVIEW_CHAR;

echo <<<HTML
<h2>Link Preview</h2>
<p>You requested the short URL <strong><a href="https://yourls.org/docs/$base/$keyword">$base/$keyword</a></strong></p>
<p>This short URL points to:</p>
<ul>
<li>Long URL: <strong><a href="https://yourls.org/docs/$base/$keyword">$url</a></strong></li>
<li>Page title: <strong>$title</strong></li>
</ul>
<p>If you still want to visit this link, please <strong><a href="https://yourls.org/docs/$base/$keyword">click here</a></strong>.</p>

<p>Thank you for using our shortening service.</p>
HTML;

yourls_html_footer();
}
更多内容 如果你想要类似 TinyURL 的预览效果(即使用 preview.domain.com 这样的子域名),就需要修改服务器的虚拟主机配置。这不是装一个插件或加一条 .htaccess 规则就能解决的事情。

评论 (0)