Quite simply, when the court considers that it would be in the best interests of the child.
To give a little more detail, if a grandparent wants to apply for a contact order, then they must first seek the leave (or permission) of the court to do so. This will be granted in most cases.
When the application is made, the court will consider it in the same way as any application relating to a child. The 'paramount consideration' is the child's welfare. Subject to that, in deciding whether to make an order the court will have regard to all of the circumstances, in particular those in the 'welfare checklist':
(a) the ascertainable wishes and feelings of the child concerned (considered in the light of his age and understanding);
(b) the child's physical, emotional and educational needs;
(c) the likely effect on him of any change in his circumstances;
(d) his age, sex, background and any characteristics of his which the court considers relevant;
(e) any harm which he has suffered or is at risk of suffering;
(f) how capable each of his parents, and any other person in relation to whom the court considers the question to be relevant (including, of course, the grandparent(s)), is of meeting his needs; and
(g) the range of powers available to the court, e.g. whether it would be more appropriate to make some other order.What does all of this mean in practice? In short, the court will in most cases take the view that contact with his or her grandparents is in the child's best interests. Accordingly, a contact order will usually be made, unless there is a good reason why it should not, such as the implacable opposition of an older child. However, a grandparent cannot normally expect to have as much contact as a parent. Thus, a typical contact order might only specify that contact should take place once a month, although there are no hard and fast rules - the type and frequency of contact again depends upon what is best for that particular child.
(Note that this is necessarily a simplification of the law. If you require more details or specific advice, you should consult a specialist family lawyer.)