You can do that in a few steps:
- Rebuild your link database
- Search for datasource items for example by template id
- For each item check if it has referrers
- Delete item
The code can looks like this:
public void Cleanup()
{
using (new SecurityDisabler())
{
var coreDb = Factory.GetDatabase("core");
var masterDb = Factory.GetDatabase("master");
// 1. Rebuild link db
Globals.LinkDatabase.Rebuild(coreDb);
Globals.LinkDatabase.Rebuild(masterDb);
// 2. Search for datasource items
var items = masterDb.SelectItems("/sitecore/content/home/*[@@templateid='{3B0461BF-9ABC-4AF1-B937-C8D225FC2313}']");
foreach (var item in items)
{
// 3. Check if item has referrers
var referrers = Globals.LinkDatabase.GetReferrers(item);
if (referrers == null || !referrers.Any() || referrers.All(x => x.GetSourceItem() == null))
{
// 4. Delete item
item.Delete();
}
}
}
}