Adding a body class based on the current Gravity Form page

Today I encountered a situation where I needed to change the background image of a page based on the Gravity Form page the user was on. Gravity Forms does not add classes outside of it’s own wrapper element, so I needed to find a way to add the current page number as a body class.

Just paste the following into your functions.php file:

// Add current Gravity Form page number as a body class
 add_filter( 'body_class', 'sm_gform_page_body_class' );
 function sm_gform_page_body_class( $classes ) {
     $num = rgpost( 'gform_source_page_number_' . $_POST['gform_submit'] ) ? rgpost( 'gform_target_page_number_' . $_POST['gform_submit'] ) : 1;
     $classes[] = 'sm_gform_page_' . $num;
     return $classes;
 }

(Code based on this StackOverflow question)

This will add a class of sm_gform_page_X to your body tag, where X is the number of the page.

From this, you could style your page as such:

.sm_gform_page_1 { background-color: red; }
.sm_gform_page_2 { background-color: blue; }
.sm_gform_page_3 { background-color: yellow; }

This might not be useful if you are using Gravity Forms as a contact form, but useful if you are creating full page surveys, registration forms or other single-use page.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.