Objective To evaluate the total, and direct effects of vitamin D, measured by circulating 25-hydroxyvitamin D [25(OH)D] levels, on GWG after adjustment for confounding variables, and then assess the indirect effects by demonstrating the role of gestational age at birth as a mediator in this association. Design A secondary analysis of data collected in a screening program in pregnancy. Setting and population Data collected in “Khuzestan Vitamin D Deficiency Screening Program in Pregnancy” was used for the present study; it was included the data of 900 pregnant women referred to the health centers of Shushtar (Khuzestan Province, Iran), whose vitamin D status during the third trimester of pregnancy was available. Methods A mediation analysis was applied to detect the causal relationship between serum level of 25(OH)D, covariates (maternal age, parity, and baseline maternal weight), mediator (gestational age), and outcome (GWG). Main outcome measures The main outcome measure of the study was gestational weight gain. Results The adjusted total effect of vitamin D on GWG was estimated 0.0699 (95%CI: 0.0537, 0.0849; P=0.000). Although, an adjusted direct effect of vitamin D on GWG was not statistically significant, the adjusted indirect effect of this micronutrient on GWG by considering gestational age as a mediator was found to be significant [0.059 (95%CI: 0.048, 0.0708; P=0.000)]. Women with severe vitamin D deficiency had the lowest speed as compared to moderate and normal levels. Conclusion This study shows that maternal vitamin D status affects the gestational weight gain by reducing the risk of preterm delivery.