Add function to every post?

I have some code that generates a dropdown list of all my post files. I would like to add this dropdown to the top of every post page, right before the post content.

What’s the correct hook/action to do so?

custom-functions.php:

<?php
function create_post_dropdown($titles){
?>
<div id=”article-choice”>
<h3>Choose an Article, or browse below</h3>
<select onchange=”if (this.value) window.location.href=this.value”>
<?php
foreach($titles as $title => $url){
echo “<option value=” . $url . “>” . $title . “</option>”;
}
?>
</select>
</div>
<?php
}
add_action(‘__after_header’, ‘create_post_dropdown’);
function add_dropdown_to_posts(){
$args = [
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => -1
];
$posts = new WP_Query( $args );
$titles = get_post_titles($args);
if (get_post_type() == “post”){
$title = $post->post_title; // get_the_title();
$title = create_post_dropdown($titles) . “<br>” . $title;
}
return $title;
}
add_filter(‘the_content’, ‘add_dropdown_to_posts’);

The idea is that when a post page is opened/viewed, this dropdown (made via create_post_dropdown) will be added before the post content.

Read more here:: Add function to every post?

Leave a Reply

Your email address will not be published. Required fields are marked *