Motivation is one of the keys to productivity, yes, so getting your motivation aligned with what you're doing is hugely important. That means understanding your goals, from big picture ("here is why I need a job" and "this is why I am at
this job") down to "this is why I'm doing
this task."
More here:
https://codewithoutrules.com/2017/08/03/stay-focused/
I've written a book about how programmers can get to a sane workweek, and one of the chapters is about how to increase productivity. It builds on the above link, but has other techniques as well. If you read the excerpts (https://codewithoutrules.com/saneworkweek/) one of the them is about a specific technique to deal with what happens when you do get unfocused and wander off track.