Implementing a Wordpress custom function - php

Site I’m working on is a radio show. I have a bunch of custom fields, courtesy of Advanced Custom Fields, for links to musicians’ websites, social profiles, etc.. For the last few years, we’ve used a Genesis child theme to display them, and the code I adapted worked great. The radio show’s host/producer now wants to move to a non-Genesis theme, and I’m having some trouble making it work.
Here’s an example from the site we’re migrating FROM, which includes the functioning code. (The Artist Links box, floated to the right of the main copy.)
Here’s the same post at the new site, where the code doesn’t yet display. (It will display in the same place.) FWIW, the theme is GrandBlog.
Here’s the code:
<?php
add_action ('if_artist_links');
function if_artist_links() {
// These are the custom field keys defined in the dashboard:
$metas_links = array(
'website',
'album',
'tour',
'twitter',
'facebook',
'bandcamp',
'soundcloud',
'youtube',
'instagram',
'linkedin',
'myspace',
'image',
);
// If _any_ ACF field is filled in, it's a go.
$has_meta = false; // init
foreach ($metas_links as $test ) {
if ( get_field($test) ) {
$has_meta = true;
continue; // Just need one meta field filled to create the div.
}
}
if ( $has_meta ) {
echo '<div class="custom-data artist-links">';
echo '<h2 class="artistname">' ?> <?php the_field('name') ?></h2>
<center><strong> <?php the_field('tribe') ?></strong></center> <?php
foreach ( $metas_links as $meta_links ) {
$$meta_links = get_field($meta_links);
if ( $$meta_links ) {
$f_object = get_field_object($meta_links);
$label = $f_object['label'];
echo '<div class="' . $meta_links . '">' .
'<span class="label">' . $label . '</span>' .
'</div>';
}
}
echo '</div><!-- /.custom-data -->';
}
}
?>`
Where there’s an ACF value, a link is created. Where there’s no ACF value, there’s no link. Just one link is required to make the box appear.
As far as I can tell, I’m not telling the code to run, or run in the right way. If you can help me do that, I’ll sing your praises through the weekend.
If possible, I’d really like to wrap this up in a WP plugin, for simplicity and ease of maintenance, and to put minimal code in single.php.
Thanks so much for your help!

You need to use WordPress the_content hook. Replace this in your theme's 'functions.php'.
function single_add_to_content( $content ) {
if( is_single() ) {
// These are the custom field keys defined in the dashboard:
$metas_links = array(
'website',
'album',
'tour',
'twitter',
'facebook',
'bandcamp',
'soundcloud',
'youtube',
'instagram',
'linkedin',
'myspace',
'image',
);
// If _any_ ACF field is filled in, it's a go.
$has_meta = false; // init
foreach ($metas_links as $test ) {
if ( get_field($test) ) {
$has_meta = true;
continue; // Just need one meta field filled to create the div.
}
}
if ( $has_meta ) {
$content.= '<div class="custom-data artist-links">';
$content.= '<h2 class="artistname">'.get_field('name').'</h2>
<center><strong>'.get_field('tribe').'</strong></center>';
foreach ( $metas_links as $meta_links ) {
$$meta_links = get_field($meta_links);
if ( $$meta_links ) {
$f_object = get_field_object($meta_links);
$label = $f_object['label'];
$content.= '<div class="' . $meta_links . '">' .
'<span class="label">' . $label . '</span>' .
'</div>';
}
}
$content.= '</div><!-- /.custom-data -->';
}
}
return $content;
}
add_filter( 'the_content', 'single_add_to_content' );
Or you can copy 'single.php' to your child theme and add this code directly without function.

Related

Displaying ACF field in page or archive head

I would like to use an ACF field to inject Schema merkup to a few specific pages on my WordPress website. Some of them are custom taxonomies or custom post types.
After a two hour research on the topic, I am still stuck.
I have created a text area field called schema_code and entered the desired Schema markup for some of my sub pages.
I currently use this code in my functions.php which does not do anything:
function acf_header_script() {
$schema = get_field('schema_code');
echo '<script type=application/ld+json>' . json_encode($schema_code) . '</script>';
}
add_action ( 'wp_head', 'acf_header_script' );
What am I missing here? Thanks a lot!
The second parameter of the ACF get_field() is required in this case, since you're not in the loop. It is either the post->ID or it's the taxonomy ID where it's {taxonomy_name}_{taxonomy_id} https://www.advancedcustomfields.com/resources/get_field/
Since you want to do this on pages and archives, etc... You need to first determine if it's a single page or an archive, etc.
function acf_header_script() {
// is it a single post?
if ( ! is_single() ) {
// no? get the queried object.
$object = get_queried_object();
if ( is_a( $object, 'WP_POST' ) ) {
$param = $object->ID;
} else {
$param = $object->taxonomy . '_' . $object->term_id;
}
} else {
// yes it's a single.
global $post;
$param = $post->ID;
}
$schema = get_field( 'schema_code', $param );
// if $schema is not empty.
if ( $schema ) {
echo '<script type=application/ld+json>' . json_encode( $schema ) . '</script>';
}
}
add_action( 'wp_head', 'acf_header_script' );

WooCommerce - not linking to products using "single product shortcode"

I would like to use the WooCommerce shortcode
[product id="99"]
However I would like to have both the product image and product name itself not link to the individual product page. All I want is the "Add to Cart" button working as intended but nothing else being clickable.
Is this possible? What template would I need to edit?
This doesn't need to be applicable to only a specific shortcode if it's easier. I never want to have people be able to get to product pages at all, so if there is a "global" way to do this, it'll work too.
Here it the logic you need to do in your functions.php, I have created a custom shortcode to get the product as you explained.
function get_c_product($atts){
$params = shortcode_atts(array(
'id' => '0',
), $atts );
$args = array('post_type'=>'product','post__in'=>array($params['id']));
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
$return = '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$_product = wc_get_product( get_the_ID() );
$return .= '<li>' . woocommerce_get_product_thumbnail() . '</li>';
$return .= '<li>' . get_the_title() . '</li>';
$return .= '<li>' . do_shortcode('[add_to_cart id='.get_the_ID().']') . '</li>';
}
$return .= '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
return $return;
}
add_shortcode('product_custom','get_c_product');
Then use the shortcode like this : echo do_shortcode('[product_custom id="99"]'); or [product_custom id="99"]

Hide Custom Field if Empty on WordPress

I've written two functions to show custom fields on the shop pages below each product, which can be viewed here. The ones specifically are Light Bulb Type and Coverage Area. However, these only apply to certain products. Right now, I am typing in N/A when they don't apply, but I would like to write a conditional statement to hide the entire section if the field is left empty.
Unfortunately, every time I do so, the code breaks the site because it is incorrectly written.
These are the functions I've written to show the custom fields.
add_action('woocommerce_shop_loop_item_title','show_coverage');
function show_coverage() {
echo '<span class="extra-info-head">Coverage Area:</span> ';
$coverage = get_post_meta( $post->ID );
$custom_fields = get_post_custom();
$coverage = $custom_fields['wpcf-coverage-area'];
foreach ( $coverage as $key => $value ) {
echo $value . '<br/>';
}}
add_action('woocommerce_shop_loop_item_title','show_bulbs');
function show_bulbs() {
echo '<span class="extra-info-head">Light Bulbs:</span> ';
$custom_fields = get_post_custom();
$bulbs = $custom_fields['wpcf-light-bulbs'];
foreach ( $bulbs as $key => $value ) {
echo $value;
}}
Apologies if these are poorly written and much appreciation to any suggestions and help!
*UPDATE: This was solved with a combination of the answer below and back-end options on WordPress's custom field posts.
Unfortunately, every time I do so, the code breaks the site because it is incorrectly written.
Your site is erroring out because you have an "undeclared variable."
In the callback function show_coverage(), you are using an undefined variable $post. The function doesn't know about this variable, because you haven't brought it into the function' scope.
While you could include the global $post, it's better to use the API function instead of the global variable.
$coverage = get_post_meta( get_the_ID(), 'wpcf-coverage-area' );
Let's go one step further. What if the custom metadata doesn't exist in the database? Then $coverage is not going to have anything in it. Let's protect for that by checking and then bailing out if nothing is returned.
function show_coverage() {
$coverage = get_post_meta( get_the_ID(), 'wpcf-coverage-area' );
if ( ! $coverage ) {
return;
}
echo '<span class="extra-info-head">Coverage Area:</span>';
foreach ( $coverage as $key => $value ) {
echo $value . '<br/>';
}
}
Now, let's do the same treatment to the other callback function:
function show_bulbs() {
$bulbs = get_post_meta( get_the_ID(), 'wpcf-light-bulbs' );
if ( ! $bulbs ) {
return;
}
echo '<span class="extra-info-head">Light Bulbs:</span> ';
foreach ( $bulbs as $key => $value ) {
echo $value;
}
}
Now the above functions will fetch the custom field (which is metadata). If it does not exist, you bail out. Otherwise, you start building the HTML markup and rendering it out to the browser.

Is there any way to have a menu with images and a custom navwalker?

I am trying to create a menu with an image, title and description.
So far, the decription and title are working great, so, I found this plugin
https://wordpress.org/plugins/menu-image/
works very good and shows the image + the title, but not the description.
So, I guess I need, somehow to show the description without losing the image.
I create a custom navwalk, but seems like I cannot just call the attached image. Looking at the code of the plugin couldnt find anything that helps.
Any idea? have anybody done this before?
My navwalker so far looks like this:
<?php
class Ext_Walker extends Walker {
var $tree_type = array('post_type', 'taxonomy', 'custom');
var $db_fields = array('parent' => 'menu_item_parent', 'id' => 'db_id');
function start_el(&$output, $object, $depth = 0, $args = array(), $current_object_id = 0) {
$classes = "";
foreach ($object->classes as $cl){
$classes.=" $cl";
}
$output .="<div class='col-lg-15 bottom-pad'>
<div class='vertical_item'>
<div class='col-lg-60'>
<div class='$classes'></div>
</div>
<div class='clear'></div>
<div class='desc_vertical'>
<h2 class='vertical_title'>{$object->title}</h2>";
if($object->post_content != ""){
$output .="<p class='item_description'>{$object->post_content}</p>";
}else{
}
$output .="</div>";
$output .="<button class='btn btn-link'>View More</button>";
}
function end_el(&$output, $object, $depth = 0, $args = array()) {
$output.='</div></div>';
}
}
?>
When WordPress is creating the menu, it is creating the menu items with links of the form
<a>Some Title</a>
The Walker runs the title through the "the_title" filter. The plugin you reference does the same thing.
So there are at least two possibilities for accomplishing you want without developing your own Walker extension:
1) Extend the plugin
Since the plugin is using the the_title filter, you could add a filter of that type to add the description (the plugin is already adding an image). So
function add_description( $title, $id ) {
if ( 'nav_menu_item' == get_post_type( $id ) ) {
$title = '<span class="title">' . $title . '</span>;
$title .= '<span class="desc">' . description from wherever you get it . '</span>;
}
return $title;
}
add_filter( 'the_title', 'add_description', 10, 2 );
This changes the text inside to link to be both title and description. You would want to check the post type, since the filter is called in other circumstances also.
2) Use just the filter
You could use a variant of the above filter to add both and image and the description, avoiding the need for the plugin. For example:
function add_img_and_desc( $title, $id ) {
if ( 'nav_menu_item' == get_post_type( $id ) ) {
// Get the image for the menu item (say in $img)
$title = $img . '<span class="title">' . $title . '</span>;
$title .= '<span class="desc">' . description from wherever you get it . '</span>;
}
return $title;
}
add_filter( 'the_title', 'add_img_and_desc', 10, 2 );
How you would get the image would depend on your approach. For example, it could be as simple as a switch statement that is based on the title.

how to create tab menu in admin page wordpress

this is my update code
if (is_admin())
{
add_action('admin_menu', 'user_menu');
}
function user_menu()
{
add_menu_page('Pesananku', 'Pesananku', 'subscriber', 'userslug',
'user_funct',get_template_directory_uri().'/img/favicon.ico',22);
}
function user_funct()
{
?>
<h2 class="nav-tab-wrapper">
Tab #1
Tab #2
Tab #3
</h2>
<div id="tab1"><!--content tab1--></div>
<div id="tab2"><!--content tab2--></div>
<div id="tab3"><!--content tab3--></div>
<?php
}
i want 'user_funct()' create tab with styling wordpress like this
http://postimg.org/image/h3nttjhof/
how to create different content with link tab menu
Thanks
Here is how you can go about it;
First, you need to create a function that create the structure depending on the current tab selected:
function page_tabs( $current = 'first' ) {
$tabs = array(
'first' => __( 'First tab', 'plugin-textdomain' ),
'second' => __( 'Second tab', 'plugin-textdomain' )
);
$html = '<h2 class="nav-tab-wrapper">';
foreach( $tabs as $tab => $name ){
$class = ( $tab == $current ) ? 'nav-tab-active' : '';
$html .= '<a class="nav-tab ' . $class . '" href="?page=ipl_dbx_import_export&tab=' . $tab . '">' . $name . '</a>';
}
$html .= '</h2>';
echo $html;
}
Then in the callback function called to display the page which will contain the tabs, you need to use this function like that:
<?php
// Code displayed before the tabs (outside)
// Tabs
$tab = ( ! empty( $_GET['tab'] ) ) ? esc_attr( $_GET['tab'] ) : 'first';
page_tabs( $tab );
if ( $tab == 'first' ) {
// add the code you want to be displayed in the first tab
}
else {
// add the code you want to be displayed in the second tab
}
// Code after the tabs (outside)
?>
Also then you call the page, you can add a GET value called tab corresponding to the tab you want to display, e.g.:
admin.php?page=my_plugin_page_slug&tab=second

Categories