这应该作为一个插件来完成,以保持它的主题独立,它只需要过滤帖子(或页面)的“内容”。这是一个使用 WooCommerce 的工作示例。它使用与您在帖子中提到的相同设计(#XXXXXX),但我建议您找到“#”以外的其他内容作为匹配的开头。这将匹配’
格式中的所有 HTML 编码字符。虽然 SKU 查找确保您不会有错误的匹配,但这意味着会有比实际需要更多的查询。
<?php
/*
Plugin Name: Replace SKU with Link
Description: Plugin to replace a formatted SKU (#XXXXXX) with the link to that product
Version: 1.0
*/
defined( 'ABSPATH' ) or die( 'No direct access!' );
class SkuReplace {
/*
* On __construct, we will initialize the filter for the content
*/
function __construct()
{
add_filter( 'the_content', array( $this, 'replace_sku_with_link' ) );
}
/**
* The filter hook get processed here
*
* @return string the filtered content
*/
function replace_sku_with_link( $content )
{
// Check if we're inside the main loop in a single post page.
if ( ( is_single() || is_page() ) && in_the_loop() && is_main_query() )
{
// Use the callback to check to see if this product exists in the DB
$content = preg_replace_callback(
'/\#[^\s\<]*/',
array( $this, 'get_product_url' ),
$content
);
}
return $content;
}
/**
* The match is checked against the product entries to verify that it exists
* If it does, it will create the hyperlink and return it, else, it returns
* the original string so as not to break the content
*
* @return string URL or original string
*/
function get_product_url( $in )
{
global $wpdb;
$sku = ltrim( rtrim( $in[0], " \t\r\n" ), '#');
$product_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1",
$sku
)
);
if( $product_id )
{
$product = new WC_Product( $product_id );
$url = get_permalink( $product_id ) ;
return '<a href="'. $url .'">'. $product->get_name() .'</a>';
}
return $in[0];
}
} // end class
$plugin_name = new SkuReplace();