php 在WordPress中更改摘录的起始点

a1o7rhls  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(54)

我的每一篇文章都以<ul class="toc_post_list">开头,在那里我有一个竞赛表。问题是,无论何时调用摘录,竞赛表都显示为摘录,而不管模板如何。
我想我可以做一个变通方案,跳过ul类,将<ul>之后的第一个<p>设置为expert,但是我的代码不工作。
以下是我尝试过的:

// Function to modify the excerpt
function custom_excerpt($excerpt) {
global $post;

// Check if the current post has a manual excerpt set
if ($post->post_excerpt) {
    return $excerpt;
} else {
    // If no manual excerpt is set, get the content and find the first <p> tag
    $content = apply_filters('the_content', $post->post_content);
    $excerpt = '';

    // Exclude content inside <ul class="toc_post_list">
    $pattern = '/<ul\sclass="toc_post_list">(.*?)<\/ul>/s';
    $content_without_toc = preg_replace($pattern, '', $content);

    // Use regex to find the first <p> tag after excluding the specified content
    preg_match('/<p>(.*?)<\/p>/', $content_without_toc, $matches);

    if ($matches) {
        $excerpt = $matches[0];
    }

    return $excerpt;
 }
}

// Apply the custom excerpt function to the 'get_the_excerpt' and 'the_excerpt' filter hooks
add_filter('get_the_excerpt', 'custom_excerpt');
add_filter('the_excerpt', 'custom_excerpt');

字符串
你知道为什么我的功能不起作用吗?

siotufzp

siotufzp1#

我改进了自定义的WordPress摘录函数,以排除特定的<ul>类并获取第一个<p>元素作为摘录,同时确保与各种HTML结构的兼容性并应用必要的内容过滤器。

function custom_excerpt($excerpt) {
    global $post;

    // Check if the current post has a manual excerpt set
    if ($post->post_excerpt) {
        return $excerpt;
    } else {
        // Get the content and apply filters
        $content = apply_filters('the_content', $post->post_content);

        // Exclude content inside <ul class="toc_post_list">
        $pattern = '/<ul\s+class="toc_post_list">.*?<\/ul>/s';
        $content_without_toc = preg_replace($pattern, '', $content);

        // Use regex to find the first <p> tag after excluding the specified content
        preg_match('/<p>.*?<\/p>/s', $content_without_toc, $matches);

        if (!empty($matches)) {
            $excerpt = strip_tags($matches[0]);
        }

        return $excerpt;
    }
}

// Apply the custom excerpt function to the 'get_the_excerpt' and 'the_excerpt' filter hooks
add_filter('get_the_excerpt', 'custom_excerpt');
add_filter('the_excerpt', 'custom_excerpt');

字符串

相关问题