Wireless Sensor Networks (WSNs) have been successfully utilized for developing various collaborative and intelligent applications that can provide comfortable and smart-economic life. This is because the majority of applications that employ WSNs for data sensing and monitoring purposes are in open practical environments, where security is often the first priority. In particular, the security and efficacy of WSNs are universal and inevitable issues. One of the most effective methods for increasing the lifetime of WSNs is clustering. In cluster-based WSNs, Cluster Heads (CHs) play a critical role; however, if the CHs are compromised, the gathered data loses its trustworthiness. Hence, trust-aware clustering techniques are crucial in a WSN to improve node-to-node communication as well as to enhance network security. In this work, a trust-enabled data-gathering technique based on the Sparrow Search Algorithm (SSA) for WSN-based applications, called DGTTSSA, is introduced. In DGTTSSA, the swarm-based SSA optimization algorithm is modified and adapted to develop a trust-aware CH selection method. A fitness function is created based on the nodes’ remaining energy and trust values in order to choose more efficient and trustworthy CHs. Moreover, predefined energy and trust threshold values are taken into account and are dynamically adjusted to accommodate the changes in the network. The proposed DGTTSSA and the state-of-the-art algorithms are evaluated in terms of the Stability and Instability Period, Reliability, CHs Average Trust Value, Average Residual Energy, and Network Lifetime. The simulation results indicate that DGTTSSA selects the most trustworthy nodes as CHs and offers a significantly longer network lifetime than previous efforts in the literature. Moreover, DGTTSSA improves the instability period compared to LEACH-TM, ETCHS, eeTMFGA, and E-LEACH up to 90%, 80%, 79%, 92%, respectively, when BS is located at the center, up to 84%, 71%, 47%, 73%, respectively, when BS is located at the corner, and up to 81%, 58%, 39%, 25%, respectively, when BS is located outside the network.