• For specific post I want to change post depending of category which is provided as additional parameter.

    I tried this:

    add_action( 'the_post', 'un_post_filter' );
    
    function un_post_filter ( $post ) {
    
      if ($post->post_type == 'page' && $post->post_name == 'mypage') {
    
        $category_name = get_query_var ('category_name');
        if (! empty ($category_name)) {
          $category = get_category_by_slug($category_name);
          $post->post_title .= ": " . $category->name;
          $post->title = $post->post_title;
        }
      }

    According to documentation and scarce examples of using action the_post this should change values and changes should be visible in HTML.

    Changes on the $post are applied as expected, but HTML still shows unaltered values.

    What I am doing wrong?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Wouldn’t you want to filter the title?


    The following is an example of filtering a title – not exactly your category case but you can see how it works

    https://gist.github.com/alanef/646695ee3ed0f38f687c623d03c3caf1

    Thread Starter pedjas

    (@pedjas)

    Yes, I was looking for that filter and I found various title filters but that one. ?? Keyword is to generic.

    the_title filter did exactly I wanted. Thanks.

    But question still stays, why changing post in action the_post does not affects displaying post?

    Moderator bcworkz

    (@bcworkz)

    the_title() get’s its post object from get_post(), it doesn’t use global $post.

    Thread Starter pedjas

    (@pedjas)

    That is what docs say: the_post is called right after query is executed containing post that is result of query.

    I wanted to change that post before it is displayed, but changes are not visible on web page.

    scope.

    your code is changing the pass argument $post not the global $post

    pass the arg as $post_arg

    the global $post

    and set that value

    cant guarantee it will work as not testing it but that is why I think you code fails

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to use the_post to change post_title?’ is closed to new replies.