piRNAs have a constitutive role in genome defence by silencing transposable elements in the germline. piRNAs also possess the ability to induce transgenerational silencing of transgenes, which can be maintained for many generations in the absence of the piRNA pathway. However, whether transgenerational silencing instigated by piRNAs has any role in adaptation to the environment is unknown. Here, we use the nematode C. elegans to test whether piRNA-mediated silencing is modulated in response to external conditions. We find that the piRNA pathway rebalances in response to a small shift in temperature, such that the majority of piRNAs, controlled by a conserved upstream motif, are downregulated. Some effects on gene expression persist into subsequent generations, which imposes a negative fitness cost. Intriguingly, simultaneous infection with pathogenic bacteria supresses downregulation of the piRNA pathway in response to increased temperature. This effect results in increased fitness of progeny of infected animals in subsequent generations. Our results show that the piRNA pathway integrates inputs from the soma to establish transgenerational responses to environmental conditions, with important consequences for the fitness of subsequent generations.