SlavisaPetkovic
SlavisaPetkovic

Reputation: 357

Place a snippet after "the_title" and before "the_content" within the Wordpress single blog post

I would like to add a small snippet right after the Wordpress single blog post title and before the single blog content.

I know that there are the_title and the_content Wordpress filters. The problem for me using these filters is that they are appended (or prepended) to the inner of it.

add_filter('the_title', array($this, 'add_snippet') );

public function add_snippet($title) {

   $snippet_html = '<div class="snippet">Snippet content</div>';
   return $title . $snippet_html;

}

Will output:

<h1 class="entry-title">Hello world!<div class="snippet">Snippet content</div></h1>

The same for the "the_content" filter:

add_filter('the_content', array($this, 'add_snippet') );

public function add_snippet($content) {

   $snippet_html = '<div class="snippet">Snippet content</div>';
   return $snippet_html . $content;

}

Will output:

<div class="entry-content single-page">
  <div class="snippet">Snippet content</div>
  <p>Welcome to WordPress. This is your first post.</p>
</div>

Is there any WP method to get a desired output like?:

<h1 class="entry-title">Hello world!</h1>

<-- HERE <div class="snippet">Snippet content</div>

<div class="entry-content single-page">
 <p>Welcome to WordPress. This is your first post.</p>
</div>

Upvotes: 1

Views: 812

Answers (1)

Neeraj Krishna Maurya
Neeraj Krishna Maurya

Reputation: 159

I don't think there are any such built-in WP methods. But of course we can achieve this by using WP hooks. Please have a look at below example.

Code in templates should be like this.

//For title
<?php do_action("your_theme_post_before_title"); ?>
<div class="title"><?php the_title(); ?></div>
<?php do_action("your_theme_post_after_title"); ?>

 //For content
<?php do_action("your_theme_post_before_content"); ?>
<div class="content"><?php the_content(); ?></div>
<?php do_action("your_theme_post_after_content"); ?>

Now you can use those hooks as per your requirement.

add_action("your_theme_post_after_title", function(){  
  echo '<div class="snippet">Snippet content</div>';    
});

add_action("your_theme_post_before_content", function(){    
  echo '<div class="snippet">Snippet content</div>';    
});

Upvotes: 0

Related Questions