Advanced Custom Fields - Wordpress - php

While using the Custom Fields Plugin, I cannot get it to return any data.
I have created a field group called book_cover_thumbnail which has one post linked to it. Can anyone see why the code below would not work?
<img src="<?php get_field('book_cover_thumbnail');?>" />
I get no errors at all, no white space.

Make sure you are a) Echoing the field using either the_field() or echo get_field(), and b) this code is either within the wordpress loop like this:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>`
<img src="<?php echo get_field('book_cover_thumbnail');?>" />
<?php end while; endif; ?>`
Or you add the post id to the get_field() function as a parameter:
$post_id = *your_post_ID_here*;
<img src="<?php echo get_field('book_cover_thumbnail', $post_id);?>" />
Documentation:
Using get_field(): http://www.advancedcustomfields.com/resources/functions/get_field/
Using the_field(): http://www.advancedcustomfields.com/resources/functions/the_field/
All Advanced Custom Fields Documentation: http://www.advancedcustomfields.com/resources/

Change get_field to the_field. Get field returns the value but doesn't echo it.
Alternatively, put an echo in front of the get field.

Little bit late but also important nevertheless:
You can change the "Return Format" in Custom Fields -> Field Groups -> Return Format
You have the choice between value/label and both(array)
Maybe that could help you in this case

Related

WordPress: Get post slug for name of module in Custom Post Type

Got a Custom Post Type called Post Modules or the slug of post-modules. In that I have created using Advanced Custom Fields a number of reusable modules to allow me to insert content in another CPT. Each module is basically a post.
What I want to do is grab the slug of the post within post-modules and display it as a class within my section. So it would be something like:
<section class="post-module-name"></section>
The title of the post would be acceptable as well.
So I came up with the following:
<section class="toolkit-module scroll-section <?php echo $post->post_title; ?> <?php echo $module_type; ?>" data-index="<?php echo $i; ?>" data-module-id="<?php echo $module_id; ?>" data-module-type="<?php echo $module_type; ?>">Content Goes Here</section>
But that pulls the title of the post that displays all these modules and not the module slugs / names themselves.
So if I have a post called "Videos" and I have two modules called let's say music-videos and sports-video, I want to incorporate music-videos in my first section's class and sports-videos in my second.
Is there some way I can pull that post slug coming from the post type and name of the module I'm actually pulling the data out of?
Check out wp_query. You’ll need to use that to access custom post types.
https://developer.wordpress.org/reference/classes/wp_query/
Yes if you already have a WP_Post object you can use it as follows.
echo $post->post_type; // Outputs the actual type of a WP_Post object
echo $post->post_name; // Outputs the slug of the post;
You can take a look at all the properties here, in your specifc case you need something like:
<section class="toolkit-module scroll-section <?php echo $post->post_name; ?> <?php echo $post->post_type; ?>" data-index="<?php echo $i; ?>" data-module-id="<?php echo $post->ID; ?>" data-module-type="<?php echo $post->post_type; ?>">Content Goes Here</section>
It looks like if I use php echo $module_id; I can display the ID number of the module, which at the very least will show something unique. Still I can't locate any documentation anywhere about how to access ACF modules beyond using module_type and module_id.
Found the solution. This did it.
$module_slug = $module->post_name;
then to display it:
<?php echo $module_slug; ?>

is_page() is not working

Ok, so I've been trying to figure this out for a while. I'm not exactly a PHP developer but can usually figure things out be looking at examples and Wordpress docs. However I'm struggling.
I'm trying to add a "simple" bit of code to a Wordpress template file, but it won't work. Basically I want to show content on certain pages and different content on other page. This is what I have so far:
<?php if(is_page('123')): ?>
This text
<?php endif; ?>
<?php if(!is_page('123')): ?>
That text
<?php endif; ?>
Any help would be so greatly appreciated.
Are you using this inside the WP Loop? If yes, note this:
Due to certain global variables being overwritten during The Loop,
is_page() will not work. In order to call it after The Loop, you must
call wp_reset_query() first.
(from: https://developer.wordpress.org/reference/functions/is_page/)
Also, you shouldn't put the page ID in quotes - it's an integer.
You should provide more context. What does the provided code echo? Does it always say "That text" although you think that it should say "This text"?
Perhaps too obvious but is '123' the name of the post?
If you want to check for the Post with the ID you should try this:
<?php if(is_page(123)): ?>
This text
<?php endif; ?>
<?php if(!is_page(123)): ?>
That text
<?php endif; ?>
Using '123' makes it a string and searches for a post with a title or slug with that string.
You shouldn't need to Logical "Not" Operator between the two statements. A simple if/else would suffice. That said:
The is_page() function will return false if the current query isn't set up for an existing page on the site.
Possible Conditions:
The global query has been modified/overwritten. If you're using query_posts() before this code - stop! Use WP_Query() along with wp_reset_postdata().
The record with the name '123' isn't actually a page. is_page specifically checks for the page post type. Consider the sister functions is_single() or is_singular().
In that same vein, are you looking for ID: 123? If so, remove the quotes. ID's should be passed as an integer: 123.
You're using this in "The Loop", where it can have unexpected interactions. You'll instead want to use another qualifying statement such as if( get_the_ID() == 123 ) ){ or if( $post->ID == 123 ){.
This code is hooked to an action hook too early such as plugins_loaded where the global query and post objects may not be set up yet.
Check to make sure whether any of those conditions apply, and then you can modify your code to be a bit more succinct:
if( is_page( 123 ) ){
echo 'This is page ID 123';
} else {
echo 'This is NOT page ID 123';
}
Or even further with the Ternary Operator
echo is_page( 123 ) ? 'This is Page ID 123' : 'This is Not page ID 123';
you could try this:
global $post;
<?php if( $post->ID == 346) { ?>
<!-- do your stuff here -->
<?php } ?>
or
<?php
if (is_page( 'Page Title' ) ):
# Do your stuff
endif;
?>

Enclosured php element in p-tag is ouside p, how is this possible?

I am using advanced custom fields in wordpress and having this line of code:
<p class="small"><?php the_field('somefield', 'options'); ?></p>
And it is printed like this in the browser:
<p class="small></p>
<p>the content of somefield</p>
Why does this happen and how do I fix it?
it's because you are using paragraph inside and paragraph you can fix it by using the fix below , if you are inserting the <p> inside this field , please use span or something else it will cause this problem if you use <p>:
<?php
$myfield = the_field('somefield', 'options');
echo strip_tags($myfield, '<p></p>');
?>
#Arsh gave a good answer.
Let me explain the inner-workings of it in WordPress Methodology.
Most function which starts with the_{function_name} most of the time has a function get_the_{function_name}.
Since the_{function_name} is a function to output the field and not threat it has data unlike get_the_{function_name}.
Here is a simple example with the_ID()
function the_ID() {
echo get_the_ID();
}
And here is an example with get_the_ID()
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
Understanding those pattern better your understanding of WordPress conventions and its inner workings.
You can always check official documentation to understand WordPress functions.
https://developer.wordpress.org/
or check in with plugin developers docs.

Using Advanced Custom Fields and Contact Form 7 to display a form

I want my users to be able to put a Contact Form 7 shortcode into a custom field in the Wordpress editor. I've created the custom field using ACF and I can pull the value onto the page, but when I try to include it in the shortcode, it comes back with a 404.
This code:
<?php echo do_shortcode(get_field('contact_form_shortcode')); ?>
Returns:
[contact-form-7 404 "Not Found"]
If I create a variable out of the value like this:
<?php
$formCode = get_field('contact_form_shortcode');
echo $formCode;
?>
The echo returns:
[contact-form-7 id="473" title="Learn More Form"]
But I get the same 404 after putting that value into the echo do_shortcode function list this:
<?php echo do_shortcode($formCode); ?>
What am I missing?
To do it With ACF pro plugin and without other extra plugins.
Create a relation field ( example: contact_form )
add the below code into your page loop:
<?php $posts = get_field('contact_form');
if( $posts ):
foreach( $posts as $p ): // variable must NOT be called $post (IMPORTANT)
$cf7_id= $p->ID;
echo do_shortcode( '[contact-form-7 id="'.$cf7_id.'" ]' );
endforeach;
endif; ?>
I was able to resolve this issue by using the technique I discussed in my comment above. By using the WYSWIG field set to 'Run filter "the_content"' I'm able to pull the field value in the way I want it. The only drawback is that users could type something else in there besides a form shortcode.
Here's my final code:
<?php
if (get_field('contact_form_shortcode')):
echo get_field('contact_form_shortcode');
else:
echo do_shortcode('[contact-form-7 id="473" title="Learn More Form"]');
endif;
?>
Instead of using a WYSIWYG field, you can simply set a Text field to "Convert HTML into tags" under the Formatting setting on the field. This will stop the 404 errors from CF7 and properly process the form. The WYSIWYG fields tend to be too hard to control from bad user input.
Here's my solution:
Create a "Post Object" type Field which will returns the post ID.
the Filter by Post Type for this field should be sett to "Contact Form" and Filter by Taxonomy leave empty.
Then in page template: (php)
<?php $contact_form = get_field('contact_form'); ?>
HTML:
<div class="col-12 col-md-8 offset-md-2">
<?php echo do_shortcode('[contact-form-7 id="'. $contact_form .'"]'); ?>
</div>
acf field screenshot
Another Solution :
1) Install https://github.com/taylormsj/acf-cf7
Installation
> 1 Copy the acf-cf7 folder into your wp-content/plugins folder
> 2 Activate the Contact Form 7 plugin via the plugins admin page
> 3 Create a new field via ACF and select the Contact Form 7 type
> 4 Please refer to the description for more info regarding the field type settings
2) Insert following code into template :
<?php if( get_field('field_acf') ):
the_field('field_acf');
endif; ?>
This applies to create a contact form 7 in a modal or Pop Up, multiple forms on the same page.
To paste CF7 shortcode (or any other generated shortcode) into ACF field as you were asking, just use the #armadadrive solution, which is exactly what question was about and it works.
create ACF text field with some name, eg hero_form
paste your shortcode into it
display contents like so <?php echo do_shortcode(get_field('hero_form')); ?>
Thanks #armadadrive
Here you can try please check the code for the shortcode below:
<?php echo do_shortcode(get_field('YourACFfieldNameHere')); ?>
I tried it on my website and it works.

Why isn't get_post_meta working?

Simple Wordpress problem - get_post_meta is not retrieving custom field values. Here's the code that is pulling from the custom fields:
<img src="<?php echo FCG_PLUGIN_URL; ?>/scripts/timthumb.php?src=<?php echo get_post_meta($post->ID, 'slider_image', true); ?>&h=250&w=400&zc=1" alt="<?php echo $post_title; ?>" />
In production, this is the HTML I get:
<img alt="Post Title" src="http://***.com/wp-content/plugins/jquery-slider-for-featured-content/scripts/timthumb.php?src=/&h=50&w=80&zc=1">
You can see the src= point in the string is empty - as if there is nothing posting from it. I have isolated and echo'd just the get_post_meta and it's a whitespace. I am 100% sure it's named correctly within the post - is there something glaring I'm missing here?
If you are calling get_post_meta inside the loop then you should call get_post_meta(get_the_id(), 'YOURKEY', true) instead of get_post_meta($post->ID, 'YOURKEY', true)
Strange things happens when you call get_post_meta inside a loop. In some themes developers hack the $post at the beginning and get_post_meta stops working so this is one of the solution for those particular cases too.
Search for the term "slider_image" in the wp_posts and wp_postmeta tables using phpmyadmin. Then view the row that has it to see if there's anything inside.
Also try changing the name of the custom value as a test and see if that works. I use this exact code to do something similar to you and it works:
<p><img src="<? bloginfo('template_url'); ?>/img/downloadresume.png"></p>
Its because of auto save.
use these lines for preventing auto save and user privileges.
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
You could also use get_post_meta( $loop->post->ID, 'yourkey', true ); if you are using $loop = new WP_Query( $args ); or something similar.
Actually, it gave you '/', which is not nothing. I'd say that's what's saved as 'slider_image'. Check the post (or the database directly).
I've written some simple templating functions that enable you to use the meta data (custom data) in your theme. You can write a template function for any meta data key/value pair, and render it in a theme file like so:
<?php the_meta_templates($meta_data_keys) ?>
<?php the_template_for($meta_data_key) ?>
Feel free to check out the basic functions from github and give them a try. You'll need to add them to your themes functions.php file.
<?php get_post_meta(get_the_id(), 'YOURKEY', true) instead of get_post_meta($post->ID, 'YOURKEY', true) ?>
Works for me!
could it be linked to the bug
#18210 (Update_post_meta is case insensitive on meta_key, but get_post_meta is NOT) – WordPress Trac
https://core.trac.wordpress.org/ticket/18210
It would explained the different experiences, depending on db_collation... (forgive me if it total nonsense, I am a newbie .. )
WordPress Database Charset and Collation Configuration | hakre on wordpress
http://hakre.wordpress.com/2010/12/26/wordpress-database-charset-and-collation-configuration/
<?php
// Get custum fields and values
$mykey_values = get_post_custom_values('my_key');
foreach ( $mykey_values as $key => $value ) {
echo "$key => $value ('my_key')<br />";
}
?>

Categories