Home Forums General Issues Trying to check for number


Trying to check for number

  • Hi good people.

    I have a custom field that is a “text box” and in there, I have tried to keep it to numbers. I haven’t made it a ‘specific number’ field, because when I did the import, some of the data in the original database was not just a number, and the import would have failed.

    Now before I display the data to the user, I am trying to check to see if it is a number (it would be an integer) before displaying the rest of the string, or “else” an alternative string. Here is my code, but I’m getting a “This site is experiencing technical difficulties” message, so I have obviously written it wrong. Please could someone with better knowledge than me take a look and show me where I am going wrong? Here is my code…

                    if get_field('ohj_height')); is_int {
                        OHJ <?php the_field('ohj_height'); Ft 
  • Hi @vgledhill

    Thanks for reaching out to us.

    Kindly try switching your code as following and let me know how it goes.

    if(is_int(get_field(‘ohj_height’))) {
    echo “OHJ”; the_field(‘ohj_height’);

    Hope to hear from you soon.

  • Thanks for your reply james, the code sort of worked, but I still have a problem.

    It now evaluates to “false” all the time, and nothing whatsoever shows up. I have tested it on an airfield that I know has just a number in that field (rufforth is 1500) I also checked in the back end.

    Is this because ACF treats all “text” fields as text?, it is therefore seeing 1500 as text and not an integer? Therefore evaluating to false?

  • Hi @vgledhill

    The text field will save its values as strings.
    For the case of the number field, you can get the raw database value by assigning a false parameter to the get_field() like so:

    $value = get_field('fieldname',false,false);

    You can also use casting within the acf/format_value to ensure that the values are loaded in a particular format:

  • Hi James. Thanks for that. Sorry for being thick, but what does that mean to this lame brain? Please could you give me an example bit of code that I need to get it to work? What you said went straight over my head.

    Kind Regards

  • Hi @vgledhill

    You can make use casting to explicitly declare a saved value into the type that you desire.
    Here is an example:

     //code goes in functions.php file
    function my_acf_format_value( $value, $post_id, $field ) {
    	// cast the value returned by all text field into integers
    	$value = (int)$value;
    	// return
    	return $value;
    add_filter('acf/format_value/type=text', 'my_acf_format_value', 10, 3);

    I hope this info helps.

Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Trying to check for number’ is closed to new replies.