如何在每篇文章的开头和结尾添加特定的文字?

问题描述 投票:0回答:2

我目前正在使用这段代码,它显示了每篇文章的代码开头。 我想在每篇文章的Beginning 和Ending 中显示代码。 有人可以帮忙吗?

add_filter( 'the_content', 'filter_the_content_in_the_main_loop' );
function filter_the_content_in_the_main_loop( $content ) {

    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {

       return esc_html__("So Friends, How is our Article of ".get_the_title().". Do You Like it? Don't Forget to Comment below if Any Queries. For More Article regarding ".get_the_title()." Subscribe Us.").$content;
    }

    return $content;
}
php wordpress post
2个回答
2
投票

你已经知道答案了。在“the_content”过滤器中,您将一些文本添加到 $content 变量中。现在你要做的是追加。例如:

add_filter( 'the_content', 'filter_the_content_in_the_main_loop' );
function filter_the_content_in_the_main_loop( $content ) {

    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
       return "Beginning text" .$content . "Ending Text";
    }

    return $content;
}

“开始文本”是您已经添加的文本。

[2020 年 1 月 7 日]:根据 OP 请求添加代码片段以根据 pos 类别进行更改。

add_filter( 'the_content', 'filter_the_content_in_the_main_loop' );
function filter_the_content_in_the_main_loop( $content ) {

    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
    //get categories
        $categories = get_the_category();
        foreach($categories as $category){
            //you can check by term_id, name, slug
            if($category->$term_id == $target_term_id){
                return "Beginning text" .$content . "Ending Text";
            }
        }
    }

    return $content;
}

0
投票

我用过这个代码。我只添加了链接。但现在代码不起作用。我可以知道如何添加链接吗?

add_filter( 'the_content', 'filter_the_content_in_the_main_loop' ); 函数filter_the_content_in_the_main_loop( $content ) {

// Check if we're inside the main loop in a single post page.
if ( is_single() && in_the_loop() && is_main_query() ) {
   return "Beginning text" .$content . "<a href="https://www.example.com/text/">Text</a>xt";
}

return $content;

}

© www.soinside.com 2019 - 2024. All rights reserved.