- 状态
- 未解决
- 主题标签
- WCML
问题概述
WooCommerce 产品简短说明基于文章摘要字段,这通常是一个不处理简码的简单文本字段。因此,如果您将页面构建器简码粘贴到文章摘要中,按理说它们是无法正常工作的,并且在翻译文章摘要时,WPML 不会尝试处理此类简码。
但是 WC 处理这些“摘要”的方式略有不同,简码确实能正常工作,但 WPML 依然将其视为无法工作,并且如果简码包含需要翻译的属性或应自动处理的内部链接,则无法轻易实现。
临时解决方法
我们准备了可作为插件添加的代码来提供此功能。将以下代码复制并粘贴到一个文件(您可以将其命名为 wpmlpb-excerpts.php)中,并保存在您的 wp-content/plugins/ 目录中,然后激活该插件。
<?php
/**
* Plugin Name: WPML Page Builders - Proces Excerpts
* Description: Parses shortcode strings in exceprts.
* Version: 1.0
*/
namespace WPMLPB686;
( new Excerpts() )->add_hooks();
class Excerpts {
const SEPARATOR_START = '<!--WPML_EXCERPT_START-->';
const SEPARATOR_END = '<!--WPML_EXCERPT_END-->';
public function add_hooks() {
add_filter( 'wpml_pb_shortcode_content_for_translation', [ $this, 'joinWithContent' ], 10, 2 );
add_filter( 'wpml_tm_translation_job_data', [ $this, 'excludeFromJob' ], 10, 2 );
add_action( 'wpml_pro_translation_completed', [ $this, 'splitFromContent' ], 999 );
}
public function joinWithContent( $content, $id ) {
$post = get_post( $id );
if ( $post && $post->post_excerpt ) {
$content .= self::SEPARATOR_START . $post->post_excerpt . self::SEPARATOR_END;
}
return $content;
}
public function excludeFromJob( $package, $post ) {
if ( preg_match( '/[[^]]+]/', $post->post_excerpt ) ) {
$package['contents']['excerpt']['translate'] = 0;
$package['contents']['excerpt']['data'] = '';
}
return $package;
}
public function splitFromContent( $post_id ) {
$post = get_post( $post_id );
if ( $post && false !== strpos( $post->post_content, self::SEPARATOR_START ) ) {
$start_pos = strpos( $post->post_content, self::SEPARATOR_START );
$end_pos = strpos( $post->post_content, self::SEPARATOR_END, $start_pos );
if ( false !== $end_pos ) {
$content = substr( $post->post_content, 0, $start_pos );
$excerpt = substr( $post->post_content, $start_pos + strlen( self::SEPARATOR_START ), $end_pos - $start_pos - strlen( self::SEPARATOR_START ) );
if ( $excerpt ) {
wp_update_post(
[
'ID' => $post_id,
'post_content' => $content,
'post_excerpt' => $excerpt,
]
);
}
}
}
}
}