How do I add a variant programmatically? I have many sites in an installation that have many Panels pages. Many of them need a HTTP Response (404) variant added to them, which I would like to do programmatically.

Assume I have the page already via:

$page = page_manager_page_load($pageName);


Modifying something in the page is easy. Make the change then call page_manager_page_save($page);

It seemed the easiest way to accomplish adding a variant was to take an exported variant and import it. This is what the clone function does.

Here is an exported variant:

$handler = new stdClass();
$handler-&gt;disabled = FALSE; /* Edit this to true to make a default handler disabled initially */
$handler-&gt;api_version = 1;
$handler-&gt;name = 'page_bes_homepage__http_response_0ab6f1a9-9c98-459c-b4d3-10f63ddace56'; 
$handler-&gt;task = 'page';
$handler-&gt;subtask = '';
$handler-&gt;handler = 'http_response';
$handler-&gt;weight = 1;
$handler-&gt;conf = array(
  'title' =&gt; '404 Error',
  'contexts' =&gt; array(),
  'relationships' =&gt; array(),
  'code' =&gt; '404',
  'destination' =&gt; '',
  'name' =&gt; '',
);


It doesn't appear necessary to set the subtask or provide a new name since the page_manager_handler_add_to_page() appears to handle that (though at first I set those myself; didn't help).

Attempting to add and save via:

page_manager_handler_add_to_page($page, $handler);
page_manager_page_save($page);


doesn't work. Some code in page_manager.module had me think that the failure might might be because of ctools caching so I tried this: 

page_manager_save_page_cache($page);
page_manager_clear_page_cache($pageName);
page_manager_page_save($page);


and that doesn't work either. Scouring the web for an example of this has not turned up anything in code snippets, tutorials or books and ctools doesn't provide this level of documentation.

How does one add a variant programmatically? Note that I do not want this in Features and I do not want this stored in code via the ctools api. I just want to run through a list of Panels pages programmatically and add a variant.
You can try this: 

I found how to store manually created variants in code for custom pages (e.g. '/node/%node/test')

function MODULE_default_page_manager_pages() {
  // Copy exported page code here.

  $pages['UNIQUE_PAGE_ID_HERE'] = $page;

  return $pages;
}


Putting everthing in a file called 'MODULE.pages_default.inc' in your MODULE's main folder, and link that file with my MODULE.module via

/**
 * Implement hook_ctools_plugin_api().
 *
 * If you do this, CTools will pick up default panels pages in
 * MODULE.pages_default.inc
 */
function MODULE_ctools_plugin_api($module, $api) {
  if ($module == 'page_manager' &amp;&amp; $api == 'pages_default') {
    return array('version' =&gt; 1);
  }
}


Source: https://www.drupal.org/node/579036