Why isn’t my cookie setting in my function?

Setting cookies is done via HTTP headers. This means you can’t set any cookies via serverside methods (PHP->WordPress) anymore after any content has been sent to the browser.

A working example of setting cookies in WordPress (in one of my plugins):

Cookie Manager: https://github.com/download-monitor/download-monitor/blob/e26022f9a96abf174a874873b8cd35a0db98882b/includes/class-dlm-cookie-manager.php

Setting the actual cookie: https://github.com/download-monitor/download-monitor/blob/e26022f9a96abf174a874873b8cd35a0db98882b/includes/class-dlm-download-handler.php#L416

The cookie is set on the hook parse_request which is triggered after init so this probably isn’t the issue in your case. Make sure there is no content send to the browser prior to your setcookie call.