Posting a comment with a photo attached has been around for a while on Facebook, but I seen any code examples explaining the process. As a result, I’ve created this brief tutorial to show how simple the API calls are. You can use the API to not only upload a new photo to a comment, but also link to existing photos uploaded elsewhere.
If you’re planning to comment on the user’s behalf, be sure to log them into the application first with
publish_actions permission – this will allow you to comment for the user using the API. If you are planning to comment using a page, be sure to get the correct
access_token for that page using the
Adding a Comment with Existing Photo
The easiest way to add a comment with a photo is to reference an existing image that’s already been uploaded, either to Facebook or elsewhere. The following code sets the basics of adding a comment with a simple message and an existing image from another website:
$facebook->setAccessToken( ACCESS_TOKEN ); line is not needed if you’re planning on logging the user in beforehand. However, you can replace the
ACCESS_TOKEN with a valid
access_token for testing purposes.
Adding a Comment and Uploading a Photo
If you prefer to upload a photo instead of linking to an existing one, that’s possible too. But a small change in the code is required – instead of using the
attachment_url parameter, you must use the
source parameter. You can even choose to not leave a message at all, and just comment with a photo – just leave out the
The below code demonstrates how to upload a photo as a comment with no message:
If you use the
source parameter, remember to prefix the path with
@ so it’s uploaded correctly to Facebook. Missing out the
@ will cause a API error or post your comment with just the
The below screenshot demonstrates the result of the two API calls above. The first comment has a message and an image from an external location, while the second comment only has the
meme.jpg image attached.