Just to clarify, inside the article view, you can get the ID of the article:
$app = Factory::getApplication();
if (
$app->input->get('option') === 'com_content'
&& $app->input->get('view') === 'article'
) {
// Get the article ID
$article_id = $app->input->getInt('id');
}
If you use the previous code inside a blog view, what you will get is the category ID.
Inside the blog view, you cant get the ID of a specific article just like before. In the blog view, you will need get the articles that category have, and then loop over them to do any task you want to accomplish. For this you will need build a query, something like:
$app = Factory::getApplication();
$factory = $app->bootComponent('com_content')->getMVCFactory();
// Get an instance of the generic articles model
$articles = $factory->createModel('Articles', 'Site', ['ignore_request' => true]);
// Get all the articles of a specific category, where $catid hold the ID of the category from where you want the articles
$articles->setState('filter.category_id', $catid);
You can apply others filters to that query as you need. When you get the articles from that query, then is when you can loop on each article and accomplish any task you want to do.
getInt()
as opposed togetCmd()
for stricter filtering. I don't know if there is a better way to get the article ID though$id = $app->input->getCmd('id', '');
gives indeed the article id... but only if you are on an Article View. If you are on a Blog View, it gives the ID of the category. In fact, I am creating an Alternate Layout of /components/com_fields/layouts/field/render.php to change the layout of some given Custom Fields. And there I need the ID of the article in order to give a unique id to the DIV. How to get that Article ID in a Blog view then?