Programatically Create 301 Redirects
The Drupal 7 Redirect module gives a site the ability to redirect from one URL to another using a proper HTTP redirect status (e.g., 301 - Permanently moved). In addition to the user interface there is a programmatic method for entering redirects.
The aptly named redirect_save function takes an object containing the details of the redirect and creates a redirect for the URL.
Here is an example of creating a redirect. A status code of 0 uses the default redirect setting which is 301, unless changed in settings.
<span style="color: #000000"><span style="color: #0000BB"><?php<br> </span><span style="color: #FF8000">// Create an object with our redirect parameters<br> </span><span style="color: #0000BB">$redirect </span><span style="color: #007700">= new </span><span style="color: #0000BB">stdClass</span><span style="color: #007700">();<br> </span><span style="color: #0000BB">$redirect</span><span style="color: #007700">-></span><span style="color: #0000BB">source </span><span style="color: #007700">= </span><span style="color: #DD0000">'the-old-url'</span><span style="color: #007700">; </span><span style="color: #FF8000">// From URL<br> </span><span style="color: #0000BB">$redirect</span><span style="color: #007700">-></span><span style="color: #0000BB">source_options </span><span style="color: #007700">= array();<br> </span><span style="color: #0000BB">$redirect</span><span style="color: #007700">-></span><span style="color: #0000BB">redirect </span><span style="color: #007700">= </span><span style="color: #DD0000">'node/1'</span><span style="color: #007700">; </span><span style="color: #FF8000">// To URL<br> </span><span style="color: #0000BB">$redirect</span><span style="color: #007700">-></span><span style="color: #0000BB">redirect_options </span><span style="color: #007700">= array();<br> </span><span style="color: #0000BB">$redirect</span><span style="color: #007700">-></span><span style="color: #0000BB">status_code </span><span style="color: #007700">= </span><span style="color: #0000BB">0</span><span style="color: #007700">; </span><span style="color: #FF8000">// Redirect Status, 0 is default<br> </span><span style="color: #0000BB">$redirect</span><span style="color: #007700">-></span><span style="color: #0000BB">type </span><span style="color: #007700">= </span><span style="color: #DD0000">'redirect'</span><span style="color: #007700">;<br> </span><span style="color: #0000BB">$redirect</span><span style="color: #007700">-></span><span style="color: #0000BB">language </span><span style="color: #007700">= </span><span style="color: #0000BB">LANGUAGE_NONE</span><span style="color: #007700">;<br><br> </span><span style="color: #FF8000">// Create the redirect<br> </span><span style="color: #0000BB">redirect_save</span><span style="color: #007700">(</span><span style="color: #0000BB">$redirect</span><span style="color: #007700">);<br></span><span style="color: #0000BB">?></span></span>
Tagged: