如何從 WordPress 文章取得特定長度文字設定為 Rank Math meta description

Rank Math 的 meta description 會被紀錄在 rank_math_description meta 中。以下是從文章內取得 200 字更新該 meta 的程式語法。

function digitspark_get_excerpt_from_content($post, $length = 55) {

    if (is_int($post)) {
        $post_content = get_the_content(null, false, $post);
    } else {
        $post_content = $post->content;
    }

    $text = strip_shortcodes( $post_content );
    $text = apply_filters( 'the_content', $text );
    $text = str_replace(']]>', ']]>', $text);
    $excerpt_length = apply_filters( 'excerpt_length', $length );
    $excerpt_more = apply_filters( 'excerpt_more', '' );
    $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    return $text;
}

$args = array(
  'post_type' => 'post',
  'posts_per_page' => -1,
  'fields' => 'ids'
);

$posts = get_posts($args);

foreach ($posts as $post) {
    $text = digitspark_get_excerpt_from_content($post, 200);
    $last_period = mb_strrpos($substring, ".");
    if ($last_period !== false) {
        $summary = mb_substr($substring, 0, $last_period + 1);
    } else {
        $summary = $substring;
    }
    update_post_met