Let $\pi:S^{2n+1}\rightarrow \mathbb{C}P^n$ denote the projection map, giving $S^{2n+1}$ the structure of a principal $S^1$ bundle over $\mathbb{C}P^n$. Let $f:X\rightarrow \mathbb{C}P^n$ be any continuous map.
There is a function $\tilde{f}:X\rightarrow S^{2n+1}$ with $\pi\circ \tilde{f} = f$ iff $f^\ast:H^2(\mathbb{C}P^{n})\rightarrow H^2(S^{2n+1})$ is the $0$ map.
(I don't remember where, but I first learned of this statement for the $n=1$ case somewhere on MSE, but if I recall, there was no proof there. I don't claim the following proof is the most elegant, it's just what I came up with.)
First, the easy direction. If $\tilde{f}$ exists, then $f^\ast = \tilde{f}^\ast \circ \pi^{\ast}$. Since $\pi^{\ast}$ is trivial on $H^2$ for trivial reasons, $f^\ast$ must be trivial on $H^2$ as well.
Now, the fun direction. Assume $f^\ast$ is trivial on $H^2$. Consider the universal principal $S^1$ bundle $S^1\rightarrow S^\infty \rightarrow \mathbb{C}P^\infty$. The Hopf bundle $S^1\rightarrow S^{2n+1}\rightarrow \mathbb{C}P^n$ is classified by the inclusions map $i:\mathbb{C}P^n\rightarrow \mathbb{C}P^\infty.$
Now, consider the composition $i\circ f:X\rightarrow \mathbb{C}P^\infty$. Recall the following bijections. $$H^2(X;\mathbb{Z})\leftrightarrow [X,\mathbb{C}P^2]\leftrightarrow \{\text{Principal }S^1\text{ bundles over} X\}$$
The bijection between $H^2(X)$ and $[X,\mathbb{C}P^\infty]$ takes an element $g\in [X,\mathbb{C}P^\infty]$ to the element $g^\ast(z)\in H^2(X)$ where we once and for all choose a generator $z\in H^2(\mathbb{C}P^\infty)$.
Since, in our case, $i\circ f$ is trivial on $H^2$, it follows that the map $X\rightarrow \mathbb{C}P^\infty$ is homotopically trivial. In particular, if we pull back the universal bundle along $i\circ f$, we get the trivial $S^1$ bundle with total space $S^1\times X$. Call this projection map $\pi_2$.
But, this implies that $f$ pulls the Hopf bundle back to a trivial bundle. Being, a pull back bundle, there is a natural map $\hat{f}:f^\ast S^{2n+1}\rightarrow S^{2n+1}$ with the property that $f\circ p = \pi \circ \hat{f}$ where $p:f^\ast S^{2n+1}\rightarrow X$ is the projection. But $f^\ast S^{2n+1}$ is bundle isomorphic to $S^1\times X$, say by a bundle isomorphism $\phi$ which covers the identity.
(I can't seem to get commutative diagrams to work, but the idea is that you have four principal $S^1$ bundles in a row, starting with $\pi_2:S^1\times X \rightarrow X$, then $p:f^\ast S^{2n+1}\rightarrow X$, then $\pi:S^{2n+1}\rightarrow \mathbb{C}P^n$, then $\pi:S^\infty\rightarrow \mathbb{C}P^\infty.$)
Now, fix a point $s\in S^1$ and consider the inclusion $j:X\rightarrow S^1\times X$ with $j(x) = (s,x)$. (That is, pick a section).
Then $\tilde{f}$ is the composition $\hat{f}\circ \phi\circ j$. This follows because \begin{align*} \pi \circ \tilde{f} &= \pi \circ \hat{f}\circ \phi\circ j \\ &= f\circ p \circ \phi \circ j\\ &= f\circ Id_X \circ \pi_2\circ j\\ &=f\circ Id_X \circ Id_X\\ &= f \end{align*}