I've a page (companies) with two subpages (new, featured).
The subpages query stuff from a custom post-type (companies). In the subpages there's also a search box that filters stuff from the custom post type.
Then, there's a banner that reads the post-thumbnail of the page "Companies" and that banner should be visible in the subpages too. I wrote this function and it works just fine for both subpages but not for the search results. It replaces the banner with the post-thumbnail of the first result, instead of the superparent (companies).
How can I fix this?.
function get_parent_post_thumb( $post ){
if ( $post->post_parent ) {
$parentId = end( $post->ancestors );
echo get_the_post_thumbnail( $parentId, 'banner' );
} else {
the_post_thumbnail( $post->ID, 'banner' );
}
}
EDIT:
I got it working with a different approach, but not as dynamic... I just put an empty field with the parent's id in the search form and then I retrieve it in the search.php template.
<input type="hidden" name="parentId" value="129" />
And then...
<?php
$id = $_GET['parentId'];
echo get_the_post_thumbnail($id, 'banner');
?>
This is not ideal but it works. Does any one have an idea on how to do it with the function I posted in the original question?
Related
So, I'm trying to do something a little complicated that's a bit above my current technical level when it comes to WordPress!
I have a custom post type called "Products". I want to be able to pull through every "post" from the Products post type into a select meta box on every other post type on the site, standard and custom alike.
Then, I want to be able to use the selection to pull through information onto the page in order to display it to the user.
I have no idea how I'd even begin doing this. I can make meta boxes and custom post types, I just don't know how to glue them all together!
I have created the same and here is the code which pulls out the post from one post-type and displays it in select tag of the post types.
You have to create a meta box and after that alone you need to pull out the posts from another post-type so that it will populate the post names in the select tag of the meta box created as follows.
I have created it for the destination_category. you can change the post_type and display place in-order to get your codes success.
<?php
//Creation of Meta Box for post type "destination_category" (Start)
add_action( 'admin_init', 'my_destination_category' );
//destination_sub_category_admin - is the required HTML id attribute
//Select Destination Sub Category - is the text visible in the heading of the meta box section
//display_destination_subcategory_meta_box - is the callback which renders the contents of the meta box
//destination_category - is the name of the custom post type where the meta box will be displayed
// normal - defines the part of the page where the edit screen section should be shown
// high - defines the priority within the context where the boxes should show
function my_destination_category() {
add_meta_box( 'destination_sub_category_admin','Select Destination Sub Category','display_destination_subcategory_meta_box', 'destination_category', 'normal', 'high');
function display_destination_subcategory_meta_box( $select_category ) {
// Retrieve Current Selected Category ID based on the Category Created
global $wpdb;
$selectcat="SELECT * FROM ".$wpdb->prefix."posts WHERE `post_type`='destination_category' AND `post_status`='publish' ORDER BY `ID` DESC";
$resultant = $wpdb->get_results($selectcat);
$rescount=count($resultant);
$category_selected_id = intval( get_post_meta( $select_category->ID, 'destination_category_id', true ) );
?>
<link rel="stylesheet" type="text/css" href="<?php echo plugins_url('css/metabox.css',__FILE__ ) ?>" />
<table>
<tr>
<td style="width: 150px">Select Category</td>
<td>
<select style="width: 100px" name="category_selection" id="meta_box_category" style="float:left; width:50%; !important">
<?php
if($rescount==0)
{?>
<option value="null">No Posts have been created</option>
<?php
}
else
{
// Generate all items of drop-down list
foreach($resultant as $singleresultant)
{
?>
<option value="<?php echo $singleresultant->ID; ?>" <?php echo selected( $singleresultant->ID, $category_selected_id ); ?>>
<?php echo $singleresultant->post_title; ?>
</option>
<?php
}
}
?>
</select>
</td>
</tr>
</table>
<?php
}
// Registering a Save Post Function
add_action( 'save_post', 'destination_admin_sub_category', 10, 2 );
function destination_admin_sub_category( $select_category_id, $select_category ) {
// Check post type for movie reviews
if ( $select_category->post_type == 'destination_category' ) {
// Store data in post meta table if present in post data
if ( isset( $_POST['category_selection'] ) && $_POST['category_selection'] != '' ) {
echo update_post_meta( $select_category_id, 'destination_category_id', $_POST['category_selection'] );
}
}
}
}
?>
I have provided here with a detailed Explanation of the code so that it will be useful for you to develop the code very easy.
hop so this will help you a lot in order to solve your problems.
I’m trying to set a sidebar in the single product page that show all products of the same categories as the product displayed.
That's how I proceed:
1) First I’ve created a sidebar called “Products_of_same_Category” to put in there a widget to show what I needed, then in function.php of my child theme I added the following snippet to execute php code in text widget:
// Enable PHP in widgets
add_filter('widget_text','execute_php',100);
function execute_php($html){
if(strpos($html,"<"."?php")!==false){
ob_start();
eval("?".">".$html);
$html=ob_get_contents();
ob_end_clean();
}
return $html;
}
2) Then when I saw that the snippet runs ok I added that code to test it:
<?php
$prod=get_the_term_list( $post->ID, 'product_cat');
echo $prod;
?>
And all worked fine, it gave me the exact name of the current category of the product displayed in the single product page.
3) So I've tried another test, deleting the previous code, to view if a shortcode translated in php should works in a widget too (writing at this time the exact category name requested, in this case "towels" - in the code below I substitute it with THE-CATEGORY-I-LIKE):
<?php echo do_shortcode('[product_category category=“THE-CATEGORY-I-LIKE” per_page="20" columns="1" orderby="title" order="desc"]'); ?>`
And all was again well done!
4) Finally I mixed all in this code to show the list of products of same categories but something goes wrong:
<?php $prod=get_the_term_list( $post->ID, 'product_cat', '', '', '' );
echo do_shortcode('[product_category category="'.$prod.'" per_page="20" columns="1" orderby="title" order="desc"]'); ?>
In last case the code doesn't display anything. I don't understand where I made mistakes, the syntax is wrong or the solving approach is illogical?
I really appreciate any help about this.
The problem is how you get the category slug. get_the_term_list will give you a formatted linked list of the categories, so it will display category names, not category slugs, which are different things. "Towels" would be your category name, but the category slug would be "towels". And product_category shortcode expect a slug, not a name.
The correct approach to get the category product slug is the following:
$terms = get_the_terms($post, 'product_cat');
if($terms && ! is_wp_error($terms)) {
foreach($terms as $term) {
echo do_shortcode('[product_category category="'.$term->slug.'" per_page="20" columns="1" orderby="title" order="desc"]');
}
}
This will display the products of all the categories associated to your product. See get_the_terms doc for reference.
In order to remove from the results the current product shown, you can make use of the woocommerce_shortcode_products_query filter. It isn't documented, but you can find it by looking at the product_category shortcode code located in includes/class-wc-shortcodes.php. In the product_category() method you will find the following line:
$return = self::product_loop( $query_args, $atts, 'product_cat' );
Where $query_args is a WP_Query parameters array. In the same class you will find the method product_loop() called here and see the following:
$products = new WP_Query( apply_filters( 'woocommerce_shortcode_products_query', $query_args, $atts ) );
So the query arguments are filtered - you will be able to work with that to add the desirated behavour. What you want to do is to use the post__not_in parameter to the query like this:
function remove_current_product_from_wc_shortcode($args, $atts) {
if(is_product()) { // check if we're on a single product page
$args['post__not_in'] = array(get_queried_object_id());
}
return $args;
}
add_filter('woocommerce_shortcode_products_query', 'remove_current_product_from_wc_shortcode');
This code should go in your theme functions.php - please not this is untested, so if it doesn't work look at the get_queried_object_id() return if it contain the current product ID.
I am using the Plugin Auto Featured Image to set thumbnails automatically. And in the database it shows updated meta thumbnail key.
But for some reason it is not showing the featured image. It doesn't show a "placeholder" neither. It just shows nothing at all.
Also, when I try to view the attachment on a single page, it does not show it.
How can I proceed to find the problem? If you need more screenshots of different tables on my database, please ask. I really appreciate your time.
EDIT
$meta_values = get_post_meta( $POST_ID, '_thumbnail_id');
error_log(var_dump($meta_values)) //Prints nothing on error log
//Note: $POST_ID is fine, it contains the right id. Problem not there.
EDIT 2:
if ( has_post_thumbnail($post_parent_id) ){
error_log("THUMB EXISTS". get_post_thumbnail_id($post_parent_id));
}
Really weird result:
THUMB EXISTS: "Blank space, No id or string at all"....
1) get post thumbnail with post id full description
<?php echo get_the_post_thumbnail( $page->ID, 'thumbnail' ); ?>
2) In a loop full description
<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail();
}
?>
3 want to get the thumb url ?? . Use this
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
<img src="<?php echo $url; ?>" longdesc="URL_2" alt="Text_2" />
I want to output the metadata from a custom field in WordPress post.
On this page if WordPress codex I found the following instruction:
To fetch meta values use the get_post_meta() function:
get_post_meta($post_id, $key, $single);
I am trying to do it this way:
<?php
get_post_meta(1, 'Currently Reading',true);
?>
But nothing gets output in the browser.
What's the proper way to output the content of the custom field?
The easiest way to do this is this:
<?php echo get_post_meta($post->ID, 'your_meta_key', true); ?>
On your post or page editor, you can go to "Screen Options" in the top right corner and check the box to display "Custom Fields". This will allow you to see the meta keys available. Just copy the name of the meta key into your get_post_meta call in the spot above where it says "your_meta_key". Don't change the $post->ID as that is global.
Taken from that page linked
<?php $meta_values = get_post_meta( $post_id, $key, $single ); ?>
so you'd need to access it through the $meta_values return object.
Like so:
<?php
print_r($meta_values);
print 'The ID is: ' . $meta_values->ID;
?>
get_post_meta(1, 'Currently Reading',true); will only get the values, you need to store it somewhere and output it properly. One way to do this is to store the function return values into a variable like so:
<?php $custom = get_post_meta( 1, $key, $single ); ?>
Then you can output it with a print or echo like so:
echo $custom;
Something to note, try using a value $post_id for the first argument. This will grab the current post id.
I'm trying to have our WP theme call in a specific sidebar when the user lands on a dedicated article/permalink page. The post category will determine which sidebar is pulled in.
Example: If the user arrives on a permalink/dedicated article page for a post categorized as "red", then the theme would look for the post category, acknowledged that the category is red, and then find and pull in the sidebar that I have defined as "red".
Just getting started with this project and would appreciate any thoughts on what I describe below.
This is what I think the code should look like to achieve that:
<?php
if (is_category()){
$current_cat = intval( get_query_var('cat') );
get_sidebar($current_cat); //for category red get sidebar-red.php
}
?>
One more piece to the puzzle:
I want to add in an addition argument so that if the post is uncategorized (i.e. we did not categorize the post for whatever reason) that it will pull in a default sidebar. I think that code should like something like this, but I don't know how to define "non-existent category". Basically I want to tell wordpress to look for the post category. If it finds that one does not exist, then I want it to pull in sidebar-default.php
<?php
if (is_category()){
$current_cat = intval( get_query_var('cat') );
get_sidebar($current_cat); }
elseif (is_category(**argument for nonexistent category**))
$current_cat = intval( get_query_var('cat') );
get_sidebar-default.php; }
?>
You should be using in_category not is.
For example:
<?php
if ( in_category('fruit') ) {
get_sidebar('1');
} elseif ( in_category('vegetables') ) {
get_sidebar('2');
} else {
// do nothing or something
// ...
}
?>
http://codex.wordpress.org/Function_Reference/in_category
<?php in_category( $category, $_post ) ?>
$category
(mixed) (required) One or more categories specified by ID
(integer), name or slug (string), or an array of these
Default: None
You can have the different sidebar classes defined in your CSS.
Give the category that you want to match up with the style the same name as that category's slug. In your template, define the sidebar div's class using the post's category-slug.
Here's a bit on how to get the slug:
<?php
if (is_category( )) {
$cat = get_query_var('cat');
$yourcat = get_category ($cat);
echo 'the slug is '. $yourcat->slug;
}
?>
So your sidebar div would be something like:
<div class="<?php echo yourcat->slug; ?> sidebar"></div>
So you've given your sidebar two classes, one called sidebar and one to be determined by whatever the category is!
Hopefully this made sense.
You can even use Category Templates, so you create category-red.php and category-blue.php files