Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

the_excerpt() function return excerpt with different length in page load and ajax request #53570

Open
Rajinsharwar opened this issue Aug 11, 2023 · 9 comments
Labels
[Block] Post Excerpt Affects the Post Excerpt Block [Priority] High Used to indicate top priority items that need quick attention [Type] Bug An existing feature does not function as intended

Comments

@Rajinsharwar
Copy link
Contributor

Rajinsharwar commented Aug 11, 2023

Description

This issue was reported by @sarathlal in WordPress core Trac: https://core.trac.wordpress.org/ticket/59043

Suppose, we are using the_excerpt() function in a post loop that displays posts from a custom WP query for the "Post" post type. Using the same query with pagination parameter and same post loop to display more posts using AJAX.
Recently it was noticed that the excerpt length was different on page load & AJAX load. Another user also raised a related support thread in the support forum.
https://wordpress.org/support/topic/unexpected-behavior-in-post-loop-after-sending-ajax-request/

It was decided that the issue needed to have fixed from Gutenburg at first, on the file:

/**
* If themes or plugins filter the excerpt_length, we need to
* override the filter in the editor, otherwise
* the excerpt length block setting has no effect.
* Returns 100 because 100 is the max length in the setting.
*/
if ( is_admin() ||
defined( 'REST_REQUEST' ) && REST_REQUEST ) {
add_filter(
'excerpt_length',
static function() {
return 100;
},
PHP_INT_MAX
);
}

Step-by-step reproduction instructions

Here is the custom code used in theme.

Code in home page template.

<?php
$current_page = get_query_var('paged');
$per_page = get_option('posts_per_page');
$offset = $current_page > 0 ? $per_page * ($current_page-1) : 0;

$blog_args = array(
    'post_type' => 'post',
    'post_status' => 'publish',     
    'posts_per_page' => $per_page,
    'offset' => $offset,
    'order'=>'DESC',
    'orderby'=>'date',
);
$blogs_query = new WP_Query($blog_args);

if ( $blogs_query->have_posts() ) { ?>
        <section class="py-3">
                <div class="container">
                        <p class="section-title">Other Blogs</p>

                        <div id="th-blog-list" class="row posts-grid gx-5 gy-4">
                                <?php 
                while ($blogs_query->have_posts()) : $blogs_query->the_post();
                    $post_id   = get_the_ID();
                    ?>
                    <?php get_template_part('template-parts/post-card'); ?>
                                <?php endwhile; ?>
                        </div>

                        <?php
                        $data = array(
                                'paged' => 2,
                                '_wpnonce' => wp_create_nonce('load-posts'),
                        );
                        global $wp_query;
                        if(isset( $blogs_query->max_num_pages ) && ($blogs_query->max_num_pages > 1)){ ?>
                                <div class="row mb-4 mt-4">
                                        <div class="col-12 text-center">
                                                <span class="spinner-border spinner-border-sm" style="display:none" id="btn-loader" role="status" aria-hidden="true"></span>
                                                <?php
                                                echo '<button type="button" class="btn btn-dark ps-4 pt-2 pe-4 pb-2" id="load-more" '. implode(' ', array_map(
                                                    function ($k, $v) { return "data-" . $k .'="'. htmlspecialchars($v) .'"'; },
                                                    array_keys($data), $data
                                                )) .' />Show more</button>';
                                                ?>
                                        </div>                                          
                                </div>                  
                        <?php } ?>

                </div>
        </section>
<?php } ?>
<?php wp_reset_postdata(); ?>

Code in template-parts/post-card.php

<?php
/**
 * Template part for displaying blog post card
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 */
?>

<div class="col-sm-12 col-md-6">
    <div class="post-item">
            <a href="<?php echo get_permalink(get_the_ID()); ?>">
                    <?php echo get_the_post_thumbnail( get_the_ID(), 'full', array( 'class' => 'f-img' ) ); ?>
            </a>
            <p class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
            <p class="short-desc"><?php the_excerpt(); ?></p>
            <p class="author"><?php echo get_the_author(); ?> | <?php echo get_the_date('F j, Y', get_the_ID()); ?></p>
    </div>
</div>
* Code in functions.php for AJAX load more

function th37t_load_more_posts() {
        $req = $_REQUEST;

        if(!isset($_REQUEST['_wpnonce'])){
                 die('stop');
        }

        if(!(wp_verify_nonce( $_REQUEST['_wpnonce'], 'load-posts'))){
                die('stop');
        }

        unset($req["action"]);
        unset($req["_wpnonce"]);

        $per_page = get_option('posts_per_page');
        $default_data = array(
                'post_type' => 'post',
                'posts_per_page' => $per_page,
                'post_status' => 'publish',
                'order'=>'DESC',
                'orderby'=>'date',
        );
        $args = array_merge($default_data, $req);

        $ajaxposts = new WP_Query($args);

        $html = '';
        if($ajaxposts->have_posts()) {
                while($ajaxposts->have_posts()) : $ajaxposts->the_post();
                    ob_start();
                    get_template_part('template-parts/post-card');
                    $html .= ob_get_contents();
                    ob_end_clean();

                endwhile;
        }

        $next_page = false;
        $max_pages = isset($ajaxposts->max_num_pages) ? $ajaxposts->max_num_pages : false;

        $current_page = isset($_REQUEST['paged']) ? $_REQUEST['paged'] : false;

        if( $current_page && $max_pages && $current_page < $max_pages ){
                $next_page = $current_page + 1;
        }
        
        $data = array(
                'html' => $html,
                'next_page' => $next_page,
        );

        wp_send_json($data);
        exit;
}
add_action('wp_ajax_th_load_more_posts', 'th37t_load_more_posts');
add_action('wp_ajax_nopriv_th_load_more_posts', 'th37t_load_more_posts');

Jquery code for "Load more" button

(function($){
	$('#load-more').on('click', function() {
		$('#btn-loader').show();
		$('#load-more').attr("disabled", true);
		var data = $(this).data();

		data['action'] = 'th_load_more_posts';

		$.ajax({
			type: 'POST',
			url: "<?php echo admin_url('admin-ajax.php'); ?>",
			dataType: 'JSON',
			data: data,
			success: function (res) {
				$('#btn-loader').hide();
				if(res.html){
					$('#th-blog-list').append(res.html);
				}

				if(res.next_page){
					$('#load-more').data('paged', res.next_page);
					$('#load-more').attr("disabled", false);
				}else{
					$('#load-more').attr("disabled", true);
				}
			}
		});
	});
})(jQuery);

Now on the initial page load, the excerpt length will be 50 words if there is no filter. But when I click on the "Load More" button, the length will be 100 words.

Screenshots, screen recording, code snippet

No response

Environment info

No response

Please confirm that you have searched existing issues in the repo.

Yes

Please confirm that you have tested with all plugins deactivated except Gutenberg.

Yes

@swissspidy swissspidy added the [Block] Post Excerpt Affects the Post Excerpt Block label Aug 11, 2023
@jordesign jordesign added [Type] Bug An existing feature does not function as intended Needs Testing Needs further testing to be confirmed. labels Aug 30, 2023
@github-actions
Copy link

Hi,
This issue has gone 30 days without any activity. This means it is time for a check-in to make sure it is still relevant. If you are still experiencing this issue with the latest versions, you can help the project by responding to confirm the problem and by providing any updated reproduction steps.
Thanks for helping out.

@github-actions github-actions bot added the [Status] Stale Gives the original author opportunity to update before closing. Can be reopened as needed. label Sep 30, 2023
@hellofromtonya hellofromtonya added [Priority] High Used to indicate top priority items that need quick attention and removed Needs Testing Needs further testing to be confirmed. labels Oct 9, 2023
@hellofromtonya
Copy link
Contributor

Hello all 👋

I've closed the Trac ticket as there's nothing actionable in that ticket as the work has to happen here in Gutenberg. But for context, I'll bring over the history.

  1. The bug was introduced in WP 6.3 with changeset 56065, see the code here https://core.trac.wordpress.org/changeset/56065#file90.

  2. For Core, the severity has been flagged as major with a high priority. As such, I've added the [Priority] High label to denote these levels of concern.

Screen Shot 2023-10-09 at 5 01 28 PM

  1. There is a PR opened for it. But discussion, review, and testing need to happen. I've also reached out to @anton-vlasenko who is interesting in helping to resolve the issue.

As this issue has been flagged as important within Core, if it gets resolved before WP 6.4 RC1, please include in the cherry picks for package updates. cc @annezazu @bph (6.4 Editor Triage Leads) for awareness.

@hellofromtonya hellofromtonya removed the [Status] Stale Gives the original author opportunity to update before closing. Can be reopened as needed. label Oct 9, 2023
@anton-vlasenko
Copy link
Contributor

I'm working on this issue.

@apeatling
Copy link
Contributor

@anton-vlasenko There's a PR opened here #53571

@anton-vlasenko
Copy link
Contributor

@anton-vlasenko There's a PR opened here #53571

@apeatling, in my tests, #53571 doesn't resolve the issue. I still see the wrong excerpt length when loading posts via AJAX requests. I'm about to submit another PR, and I'm currently testing it.

@apeatling
Copy link
Contributor

Okay 👍

@anton-vlasenko
Copy link
Contributor

anton-vlasenko commented Oct 17, 2023

@apeatling I've submitted my pull request. It's ready for testing. I'll add better testing steps tomorrow (it's deep into the night in my time zone), but it can be tested as is.

UPD: I've updated the testing instructions.

@swissspidy
Copy link
Member

In https://core.trac.wordpress.org/changeset/58065 I just added support for the excerpt_length parameter in the REST API.

This can now be used in the post excerpt block to properly modify the excerpt length in a non-hacky way.

@colorful-tones
Copy link
Member

Hi folks,
We are only one week away from the Beta 1 cut-off date for WordPress 6.6. This issue hasn’t seen any movement in a while, so we (the editor triage leads of the 6.6 release) have decided to remove it from the WordPress 6.6 Editor Tasks project board.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Block] Post Excerpt Affects the Post Excerpt Block [Priority] High Used to indicate top priority items that need quick attention [Type] Bug An existing feature does not function as intended
Projects
None yet
7 participants