1

I'm trying to add a button for each post.

add_action( 'the_post', [ $this, 'myButton' ] );
public function myButton( $post ) {

      $this->ID = $post->ID;
      $myId=$post->ID;
      echo "<button onclick=\"buttonAction()\" p style=\"font-size:10px\" id=\"ActionButton\">ACTION</button>";
}

This works well, but there is a problem, it not only appears in post, but also on homepage above each post and at all pages that contains a link to post. Additionally I can't style for displaying it at the proper place, it is on the top of post. How can i style it, and make it only appear on post's webpage.

2

Use the_content hook and hook only when you are on a single page:

add_filter( 'the_content', 'my_button_function' );

function my_button_function( $content ) {

    // See if it's a single post or a loop
    if ( is_single() && in_the_loop() && is_main_query() ) {
        return $content . "<button onclick=\"buttonAction()\" p style=\"font-size:10px\" id=\"ActionButton\">ACTION</button>";
    }

    return $content;
}

This will only add the button if you are on a single post, and will add the button at the end of your content.

Further reading at : WordPress Developer's website.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.