What exactly do you mean ?
Look, suppose we have a ferromagnetic material which is caracterized by the fact thal all atom spins will align due to magnetic interactions between neigboring atoms. This results in a permanent magnetization beneath some critical temperature. You need to know that the specimen is actually devided into many local areas called the domains and the atoms in each domain are all aligned in the same direction. However, two different domains each can have a different direction in which all atoms are aligned.
Now, we apply a magnetic field B along the z-axis
The potential energy U (see above formula) will be lowest when the magnetization (or the magnetic moments) is parallel to the B-field. So indeed, there will be an attempt of the atoms to align their spin in the B-direction.
But the specimen is actually divided into many domains in which the atoms are all aligned in the same direction. However each domain has a different magnetic moment (ie : magnetization). So some magnetizations will already be aligned along the z-axis and others will have an angle with the B-field. However, and i think that is what you mean, the B-field will try to lower the potential energy by directing the magnetic moments of each domain (denoted by the magnetization vector) along the B-field.
The alignment of the magnetic moments towards the B-field can be made difficult by a concept called anisotropy.There is indeed an influence of the crystal structure and the shape of grains on the direction of magnetization. The dependence of magnetic properties on a preferred direction is called magnetic anisotropy. There are several different types of anisotropy:
Type depends on
1. magnetocrystalline- crystal structure
2. shape- grain shape
3. stress- applied or residual stresses