skip to Main Content

When using CF7 (Contact Form 7) is there any way to get the placeholder text from a php function?
I’ve tried using a shortcode to call the php function, but it doesn’t work.
Here is my test:

function.php code:

add_filter( 'wpcf7_form_elements', 'do_shortcode' );
add_shortcode( 'get_placeholder', 'get_placeholder_func' );
function get_placeholder_func () {
    return "Hello world";
}

CF7 template:

[get_placeholder]
[text the-field placeholder [get_placeholder]]

First line works fine and outputs the text returned from the php function.
Second line doesn’t work as it only outputs a end-bracket.

I know I can do it by using js/jQuery, but it is a bit messy.
Can anybody help? Thanks 🙂

2

Answers


  1. Why don’t you try the following:

    Define the function

    function get_placeholder_func () {
        return "Hello world";
    }
    

    Then create your own input for CF7

    wpcf7_add_form_tag('custom_text_input', 'wpcf7_custom_text_input');
    function wpcf7_custom_text_input($tag) {
        if (!is_array($tag)) return '';
    
        $name = $tag['name'];
        if (empty($name)) return '';
        $placeholder = get_placeholder_func();
    
        $html = '<input type="text" name="'.$name.'" placeholder="'.$placeholder.'" />';
        return $html;
    }
    

    Then, when editing CF7 you just have to call the input created

    [custom_text_input name-of-input]
    

    This shortcode will have name-of-input name and placeholder declared by the function get_placeholder_func()

    Hope it works.

    Login or Signup to reply.
  2. I’m a little unclear as to why you would want to do this, but here’s a method.

    add_filter( 'wpcf7_form_elements', 'cf7_replace_a_string' );
    function cf7_replace_a_string( $content ) {
        // Name = Form Tag Name.
        $str_pos = strpos( $content, 'name="the-field"' );
        // If your form field is present.
        if ( false !== $str_pos ) {
            $placeholder = 'this is your placeholder';
            $content     = str_replace( 'placeholder="placeholder"', 'placeholder="' . $placeholder . '"', $content );
        }
        return $content;
    }
    

    Then your form tag would look like this:

    [text the-field placeholder "placeholder"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search