\cref inside a heading breaks PDF bookmark
You have (re)discovered a fundamental limitation of TeX's ability to process certain items that will go into things like bookmarks. Note that this limitation isn't limited to processing \cref
instructions.
To get around this limitation, you can employ the (admittedly somewhat kludgy) command \texorpdfstring
, which takes two arguments. The first is what should be displayed on the "TeX side" (which comes down to, basically, what should be shown in the body of the text), and the second is what should be displayed on the "pdf side" of things, such as in the bookmarks.
A modified form of your MWE would thus look like this:
\documentclass{article}
\usepackage{hyperref}
\usepackage[capitalize,nameinlink,noabbrev]{cleveref}
\hypersetup{%
bookmarksnumbered, bookmarksopen=true, bookmarksopenlevel=1,%
}
\begin{document}
\section{foo} \label{sec:foo}
\section{Code for \texorpdfstring{\cref{sec:foo}}{Section \ref{sec:foo}}}
\end{document}
The first argument will generate a hyperlink from the text of the second sectioning header to the first, and the second argument provides information as to what shows up in the bookmarks. With this setup, the bookmark for the second section will read "Code for Section 1".