Guanchishan / import-from-mastodon

Automatically turn toots—short messages on Mastodon—into WordPress posts.
GNU General Public License v3.0
0 stars 0 forks source link

让可从嘟文中提取的作为WP标题的词数上限可由用户选择 #1

Open Guanchishan opened 1 year ago

Guanchishan commented 1 year ago

这段代码:$title = wp_trim_words( $content, 10 ); 涉及到导入内容在wordpress提取前多少个词作为标题。这个10数字做成在WP仪表盘让用户可以自由指定。

需要将这个数字改为一个选项,这样用户就可以在WordPress仪表盘中进行设置。这涉及到两个步骤:首先需要在仪表盘中添加一个新的设置字段,然后在代码中使用这个设置。

第一步,添加设置字段。这个可能需要在某个适合的设置页面,如“Import From Mastodon”的设置页面中添加新的设置字段。这通常在一个WordPress管理界面的某个钩子函数中完成,如下所示:

function add_settings_field() {
    add_settings_field(
        'trim_words_count',                              // The ID (or the name) of the field.
        __( 'Trim words count', 'import-from-mastodon' ), // The title (to be displayed).
        'trim_words_count_callback',                      // The callback function to render the input field.
        'import_from_mastodon_settings',                  // The page on which to display this field.
        'import_from_mastodon_settings_section'           // The section on which to show the field.
    );
}
add_action( 'admin_init', 'add_settings_field' );

// The callback to render the input field.
function trim_words_count_callback() {
    $options = get_option( 'import_from_mastodon_settings' );
    echo '<input type="text" id="trim_words_count" name="import_from_mastodon_settings[trim_words_count]" value="' . esc_attr( $options['trim_words_count'] ) . '">';
}

第二步,使用设置。需要将wp_trim_words调用更改为以下形式:

$options = get_option( 'import_from_mastodon_settings' );
$trim_words_count = isset( $options['trim_words_count'] ) ? $options['trim_words_count'] : 10;
$title = wp_trim_words( $content, $trim_words_count );

注意,如果用户没有设置这个选项,我们默认使用10(或者按照0.3.3版的30)作为单词计数。

上面的代码只是一个简单的例子,可能需要根据具体需求对其进行适当的修改。例如,可能想要添加一些验证或清理逻辑来确保trim_words_count总是一个正整数。可能还要在trim_words_count_callback函数中添加一些帮助文本,向用户解释这个设置的用途。