INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to split the site's layout without damaging this layout?
I have a site: < and I need to migrate it to wordpress (to be particular, I need in the nearest perspective it's plugins and ability to login thgrough the social networks via wordpress plugins)
I ought to split this design up into header.php, content.php and footer.php without any damaging the content and layout. We don't need to display any posts yet so instead of them should be added a placeholder like an arbitrary article.
Now we're using the Bitrix as a CMS, headroom.js, several inner Bitrix templates which form the current design and they're kind of bulky so we wouldn't like to rewrite all of them.
Is it possible to port this site on wordpress this way as I described? | Better thing is that if you have all pages in html format of you current site , following will help you to convert html to wordpress as per your given partition :
| stackexchange-wordpress | {
"answer_score": -2,
"question_score": -2,
"tags": "theme development, customization, page template"
} |
Getting specific image thumbnail urls of attached images
I am using the Manual Image Crop plugin to set thumbnails for images. I am not using any images as 'featured images' however.
I have a number of thumbnails saved to each image. If I use `wp_get_attachment_link(id, 'medium');` then I get the desired 'medium' thumbnail returned but as whole html block output, including '' tags, size etc etc.
I just want the URL of this specific thumbnail (or the img tags 'src' attribute). Is there a built in wordpress function for this or will I have to use PHP regex or something? | Have a look at wp_get_attachment_image_src
<?php
$attachment_id = 8; // attachment ID
$image_attributes = wp_get_attachment_image_src( $attachment_id, 'medium' ); // returns an array
if( $image_attributes ) {
?>
<img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>">
<?php } ?>
Source: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "thumbnails"
} |
get "read more" with custom DB query like you would with WP Query
I am using a custom database query to fetch posts.
In the post I have a break tag, which is displayed as `<!--more-->` in the database wp_posts table, but I can't get it to output like I would if I used `wp query`. It is basically ignored.
i tried using `apply_filters` like so, but to no avail:
<?php echo apply_filters("the_content", $post->post_content); ?>
I don't get either the "read more" anchor or the "read more" span tag in the post's content.
How can I get it with my custom query? | The `<!-- more -->` tag isn't applied via the `the_content` filter, it's included in the `get_the_content()` function, which checks for the existence of the tag within the content using a regex and then outputs the more link appropriately. this output is filtered via the `the_content_more_link` filter, but since you're not using `get_the_content()` you won't be able to leverage that. you'll need to perform a similar regex replacement in our custom code. I would recommend filtering your more link via `the_content_more_link` as well, for compatibility. You can see the code `get_the_content()` uses here: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, query posts, read more"
} |
Which custom post type does the current post belong to?
I have looked all over the Codex and searched the web and I cannot find a way to accomplish what I am trying to do. All I need to do is display what CPT a post belongs to. For instance, I have two different post types, Courses and Resources, and I need a way to output which one of these a particular post belongs to. Can anyone help? | `get_post_type()` should do what you're asking. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
Register Script in Plugin Widget
I need to load a separate js file into a widget and just can't get it to work. So far I have
if ( is_active_widget( false, false, $this->id_base, true ) ) {
function tab_widget_scripts() {
wp_register_script( 'tabs', plugins_url( 'tabs.js', __FILE__ ), array(), false, true );
wp_enqueue_script( 'tabs.js' );
}
}
in my `function __construct()` and then
do_action( 'wp_print_footer_scripts', 'tab_widget_scripts' );
inside `public function widget( $args, $instance )`. Can anyone tell me what I'm doing wrong please? | There are 3 issues.
Firstly, you're calling `do_action`, triggering the action:
do_action( 'wp_print_footer_scripts', 'tab_widget_scripts' );
When actually, you want to add your function to it, not trigger it. You should be doing this:
add_action( 'wp_print_footer_scripts', 'tab_widget_scripts' );
Secondly, you're registering this script:
tabs
Then enqueuing this script:
tabs.js
Clearly they don't match, in the same way that if I give you the ingredients for cake then tell you to make a latte, it isn't going to work.
Thirdly, you only define the function if the widget is shown on the frontend. This is a little odd, instead you should use `add_action` on your function in your widget class, and always define it, saving yourself an unnecessary call to `is_active_widget` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, widgets, scripts"
} |
Display all posts from selected month
I am trying to display all posts from a selected month.
Currently once I select a month, only 10 posts display. I understand I can increase the amount of posts to show under the 'reading' options within the dashboard.
I want to be able to keep the front posts page to display 10 posts but the 'archive' pages to display all posts.
Any help appreciated. | You can use the `pre_get_posts` action to set `posts_per_page` to `-1` on the monthly archive pages.
I said wrongly in a comment to use `is_archive()` as your conditional. The problem with `is_archive()` is, it returns true on all archives, which includes category and taxonomy archive pages as well.
I would suggest to make use of `is_date()` and `is_month()` if you specifically needs to target montly archives
( _Please note, the following code is untested and needs PHP 5.3+_ )
add_action( 'pre_get_posts', function ( $query ) {
if ( !is_admin() && $query->is_date() && $query->is_month() && $query->is_main_query() ) {
$query->set( 'posts_per_page', '-1' );
}
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, archives, list"
} |
Category with description and thumbnail
I am using the below codes to show all Parent Terms from a custom taxonomy with title and link on a page. But I want to show the parent term description, thumbnail and post count in it too. So how I can get those too (alongside title and link)?
$all_categories = get_categories( array(
'taxonomy' => 'product_cat',
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 1,
'title_li' => '',
'hide_empty' => 0,
) );
foreach ( $all_categories as $cat ) {
if ( $cat->category_parent == 0 ) {
$category_id = $cat->term_id;
echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>'; ?>
}
}
Note: I will give warm welcome to those who also help me to short the upper code more as I think it have some extra stuff. | I was trying after posting here too and I got my snippet and here I am also sharing it so you can also get it. I used the code shared at **Display WooCommerce Products Categories With Thumbnail& Description**. It also shows **Title, Link, Product Count In It, Thumbnail, Description and Custom Text** so this is my solution. Hope you will find it worthy too. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, categories"
} |
Enqueue stylesheet in plugin for wp-login.php
# What I have:
A basic plugin that's calling a stylesheet contained in the plugin folder:
function my_login_enqueues() {
// First attempt:
//wp_enqueue_style( 'custom-login', 'style-login.css' );
// Second attempt:
$plugin_stylesheet = plugins_url( 'style-login.css', __FILE__ );
wp_enqueue_style( 'custom-login', $plugin_stylesheet );
}
add_action( 'login_enqueue_scripts', 'my_login_enqueues' );
# My problem:
I'm receiving the following heading error at wp-login.php:
> Warning: Cannot modify header information - headers already sent by (output started at [...]) in [...]/wp-content/plugins/members-only/members-only.php on line 398
**Note:** The Members Only deals with wp-login.php.
# My question:
How can I apply a style-sheet to wp-login.php using a plugin?
**Note:** I'm knowingly not using functions.php on a per theme basis. | You can do this two way.But I prefer to go for the second way.You need to put this code in your plugins file.
First way:
function my_loginlcustomization() {
echo '<style type="text/css">
h1 a {
background-image: url(' . plugin_dir_url( __FILE__ ).'/login/logo.png) !important;
}
</style>';
}
add_action('login_head', 'my_loginlcustomization');
Second Way(I prefer):
function my_loginlcustomization() {
wp_register_style('custom_loginstyle', plugins_url('/css/login.css', __FILE__));
wp_enqueue_style("custom_loginstyle");
}
add_action('login_head', 'my_loginlcustomization');
Thanks | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, headers, wp enqueue style, wp login form"
} |
Default taxonomy 'post_tag' added to CPT managing by custom role : nothing in the metabox
I've created a Custom post type, which a custom role can manage : it has only the capabilities for managing this CPT.
When registering the CPT, I've set the argument : 'taxonomies' => array( 'post_tag' ) But when I go to the form of this CPT logged in as a user in the custom role, I can see the Metabox "Tags", but only the title header, there is nothing in the box.
I've not found any capability for giving it to the custom role.... How could this be fixed ?
Thx ! | I guess your custom user role does not have the required capability to assign terms, which in case of the `post_tag` taxonomy would be `edit_post`.
So one thing to do would be giving it to your role--which is most likely not what you would like to do as this does not only affect assigning terms but also a number of other actions).
Another thing you could do is using the `map_meta_cap` function. If you choose to take on this approach and you have any problems, just say so, and I will try to help you. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, metabox, taxonomy, tags, user roles"
} |
Wordpress Recent post only showing title
I'm new in wordpress theme development. I want to display recent posts via recent post widget. but when I active the Recent posts widget in wordpress admin panel it only shows the title but not the images. But when i write a custom code in sidebar it works fine. I want to work it like a widget perfection. I do not want to use any plugin, help me in custom code. | Have a look at the `WP_Widget_Recent_Posts` class in `wp-includes/default-widgets.php` to see how it is structured.
You can even copy and paste the class in your `functions.php`, rename it to something else and modify the class to display your images.
And don't forget to add a `register_widget('NameOfYourClassHere');` hooked to `widgets_init`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "recent posts"
} |
Multiple Custom Post Type permalink issue
I have 2 Custom Post Type(Our Works and Case Study) in a WordPress site. If I add same postname(Pepsi) at my 2 Custom Post Type(Our Works and Case Study) the permalink will show given below:
1) www.example.com/our-works/pepsi/
2) www.example.com/case-study/pepsi-2/
But It should be like:
1) www.example.com/our-works/pepsi/
2) www.example.com/case-study/pepsi/ | Thanks cybmeta I have installed a plugin called Allow Duplicate Slugs By John Blackbourn and fixed issue! also I come across another function.php solution too. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, permalinks, rewrite rules"
} |
Wordpress plugin problem with encoding
Ok I made wordpress contact form plugin. Basiclly in form i have dropdown list of states loaded from database. In db i have country name in Romanian. For example
Federaţia Rusă
Polinezia franceză
Jamahiriya Arabă Libiană
Iran, Republica Islamică
Dispite when i click page source in my header i have UTF 8, but countries name are loaded in row format, other countries are loaded correctlly. For example
România | Uncommented constant db `define('DB_CHARSET', 'utf8')` in config.php file | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "encoding"
} |
Get custom category ID of current custom post within the loop
I am having extreme difficulties retrieving the name (or the ID) of the current category of the custom post being viewed (within the loop).
The current category name is "school" and it is a subcategory of the custom category called "category_news"
I am trying the following, but it returns empty.
$terms = get_the_terms( $post->ID , 'category_news' );
if ( $terms != null ){
foreach( $terms as $term ) {
print $term->slug ;
unset($term);
}
} | get_the_terms( $id, $taxonomy );
second parameter should be your taxonomy name instead of category name | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
Adding a query string to only one page url
I would like to add the following to a single page within my wordpress site and NOT all of them.
Current page url/permalink
mysite.com/pagename/
Would like to
mysite.com/pagename/?ngg_force_update=1
This is so that the nextgen plugin does not use a cached template, as the one i created for it does random stuff on page loads/refresh etc.
And rather than set the values within the actual plugin and have them over written via an plugin update, the url query is the only why, that i know of, but i don't want to add it to all url's etc just that pages permalink. | You can filter `page_link` to modify the output of any page's permalink value. The simplest way to identify the page is by ID, then you can append the query string via `add_query_arg`:
function wpd_append_query_string( $url, $id ) {
if( 42 == $id ) {
$url = add_query_arg( 'ngg_force_update', 1, $url );
}
return $url;
}
add_filter( 'page_link', 'wpd_append_query_string', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "url rewriting, urls"
} |
Why do themes rely on "The Loop"?
I've been looking at Wordpress themes development recently, and I'm trying to understand why Wordpress is coded with "The Loop", rather than providing an array of posts that you can loop through with a foreach.
It just seems to add complexity for theme development, but surely if they went out of there way to create this concept of "loop" there must be a reason? | You are thinking of WordPress templates as PHP application code. Essentially they are not that.
WordPress templates by design are templates using Template Tags API. It is extra level of abstraction, that just happens to allow to use rest of PHP language too.
The ease of template tags serves the popularity of WordPress and extremely low entry bar for people to tweak themes. Believe me, there are plenty of people around who use/tweak loops without much understanding of what they actually are, in extreme cases, what **arrays** even are. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 6,
"tags": "loop, themes"
} |
Undefined property: stdClass::$id when retriving term ID
I have the following:
foreach( $this_post_terms as $term ) :
$thiscat = get_term_by( 'slug', $term->slug, 'categories_whatever' );
echo $thiscat->ID;
endforeach;
The last line throws an error, Undefined property: stdClass::$ID.
What's weird to me is that
echo $thiscat->name;
works, doesn't throw any error. | The fields returned by `get_term_by()` are:
* term_id
* name
* slug
* term_group
* term_taxonomy_id
* taxonomy
* description
* parent
* count
So instead of `$thiscat->ID`, you should use `$thiscat->term_id`
Ref: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
What is the design pattern for WordPress Core?
What is the design pattern of WordPress Core? As this Stack Overflow question shows, WordPress does _not_ follow the MVC pattern; however, developers can write plugins and themes that follow MVC. But my question pertains _exclusively_ to WordPress Core, not to any additional add-ons, themes, extensions, plugins, or forked projects that may or may not follow an MVC pattern.
If WordPress Core does not follow an MVC design, then what design pattern does it follow? | Spaghetti with meatballs
> The term "spaghetti with meatballs" is a pejorative term used in computer science to describe loosely constructed object-oriented programming (OOP) that remains dependent on procedural code. It may be the result of a system whose development has included a long life cycle, language constraints, micro-optimization theatre, or a lack of coherent coding standards.
It also has a bit of macaroni mixed in...
< | stackexchange-wordpress | {
"answer_score": 23,
"question_score": 16,
"tags": "design"
} |
What happens when WordPress memory limit is exceeded?
Let's say a WordPress website has the following settings:
* PHP Memory Limit: 100MB
* WordPress Memory Limit: 50MB
What happens when the WordPress Memory Limit is exceeded?
1. Do plugins/themes stop / Do processes fail?
2. Does the website hang on the back-end/front-end?
3. Are public website visitors presented error messages or is it all a background affair?
Why is it a bad idea to set it too high? | There isn't really such a thing as _separate_ WP memory limit. It's just a WP way with messing with PHP setting, instead of just using... you know... PHP for that.
* If WP limit is more than PHP limit then WP will attempt to increase PHP limit (which doesn't mean it will succeed at that, but it will try).
* If WP limit is less (such as in your example) then it is simply ignored.
The practical _need_ for a limit is too prevent PHP from draining more memory than server can realistically spare. Hosts usually have hard maximum limit, you won't be able to go above via configuration.
So the answer to your question is — exceeding WP memory limit is meaningless, what matters is exceeding real PHP limit. In which case page will crash with fatal error.
Note that memory limit affects each execution/page view, not a site as a whole. So might be crashing as much as completely everything and as little as one individual page. Whatever is leaking or overusing memory. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, php, memory"
} |
Wordpress custom form post to different page
I have a site which is developed with `PHP` and recently I added `Wordpress` blog(same domain with `/blog` url) to that.
I would like to implement two extra functions(subscribe/contactus) on that blog which is already existing & handling on `PHP` site.
I found few plugins like `Visual Form Builder` to build custom forms and also widgets.
I need to use existing php back-end functions to handle contact-us and subscription functionality in the blog as well. My question is how to change the action url on those custom build forms(in the blog) to post details directly to that existing functions in the `PHP` site.
Note : i'm very new to wordpress. | If you choose to use `contact form 7` plugin then you can find very detailed instructions here. Basically you need to create a custom filter using `wpcf7_form_action_url` hook.
Another option would be to create child-theme and create your custom form there, but that IMHO would be a bit of an overkill. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "urls, forms"
} |
While loop with an exception after a count is reached
I'm trying to edit the tag.php page so that it displays all tagged posts (as it normally does) 'but' I want to call a function after the 3rd post in the loop.
Current Code
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
Any suggestions on how to insert the following function after the **3rd** post in the loop?
<?php echo someFunction() ?> | You can make use of the build in loop counter, `$current_post` which you can access in the main query with `$wp_query->current_post`. ( _Just a note, the counter starts at`0`, so post `1` will be `0`_)
The main query uses `WP_Query`, `$wp_query` being the query variable used, so have a look at the Methods and Properties which you can make use of and the uses of these Methods and Properties
Inside your loop, just before `endwhile`, add the following
if( 2 === $wp_query->current_post ) {
echo someFunction();
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, loop"
} |
How can I add few css or js file into my plugin
I want do add few cs and js file into my plugin in admin panel. I create function style:
function style() {
wp_enqueue_style ( 'my-admin-theme', plugins_url ( 'style.css', __FILE__ ) );
wp_enqueue_script ( 'jquery', ' array (), '1.0.0', true );
wp_enqueue_script ( 'uploadfile', ' array (), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'style' );
add_action( 'wp_enqueue_scripts', 'style' );
add_action ( 'admin_enqueue_scripts', 'style' );
add_action ( 'login_enqueue_scripts', 'style' );
When I check source code I see only style.css jquery.uploadfile.min.js. What is wrong ?
King regards | if( ! function_exists( 'style' )){
function style() {
wp_enqueue_script('jquery');
wp_enqueue_style ( 'my-admin-theme', plugins_url ( 'style.css', __FILE__ ) );
//wp_enqueue_script ( 'jquery', ' array (), '1.0.0', true ); // already included jQuery
wp_enqueue_script ( 'uploadfile', ' array (), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'style' );
add_action ( 'admin_enqueue_scripts', 'style' );
add_action ( 'login_enqueue_scripts', 'style' );
}else{
echo 'Function already exists';
}
Try next code, but your code work. No need to include jQuery, because by default WP use it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins"
} |
List Terms by category
I have a custom taxonomy called `portfolio-type`. The `terms = post_type` is `portfolio` and category is `portfolio-type`
I'm trying to fetch related post of the same category of current post
<?php
global $post;
$terms = get_the_terms( $post_id, 'portfolio-type' );
$terms = $terms[0]->cat_ID;
$myposts = get_posts(array('numberposts' => 5, 'offset' => 0, 'post_type' =>'portfolio', 'category__in' => wp_get_post_categories( $post_id, 'portfolio-type' ), 'post__not_in' => array($post->ID), 'post_status'=>'publish', 'order'=>'ASC' ));
foreach($myposts as $post) :
setup_postdata($post);
?>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
The script shows related posts however doesn't show current post. I'm using this code for showing related posts as a sidebar menu. | Your query explicitly excludes the current post with this:
'post__not_in' => array($post->ID),
remove that and it will return the current post within the results. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, custom taxonomy, terms"
} |
Loading custom CSS
I've done some searching and can't seem to find the appropriate solution for a particular problem I'm having. I've created an option within one of my themes that allows the user to edit any element such as h1, p, divs, etc. The user can also add styling and I basically just build up a string of identifiers and the styling that the user has chosen.
What's the best way to load this css string? Is it best to just have it as a function call before , or should I programmatically create a 'custom.css' file that then gets enqueued after 'style.css'? I worry about creating a 'custom.css' file just in case permissions become an issue. | Well one option you could do, is wrap them in style tag and stuff them into the header via a filter. It's dirty, but it would work. I'd honestly do that, over forcing inline styling on elements, because they won't get cached. Plus anyone who wants to do their own styling to override those elements will hate you.
The cleanest way WOULD be in fact to create a custom.css file dynamically. File Permissions shouldn't be an issue within a theme or plugin environment in MOST installs, however in cases where it is, you can issue a warning to the site admin about it. If you opt for this route, you could do a file permissions check before hand, and default to one of the other methods in the event you don't have adequate permissions. That'd be the most fail-safe way of doing it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp enqueue style"
} |
Displaying custom post types in front end
I am trying to wrap my head around custom post types. What I am trying to achieve is a simple branch listing. There is a dealers menu that has drop downs with regions. When you click on a region I just want it to list branches within the region. Nothing fancy, no maps, just plain text with branch name and contact details + address. Something like this:
Branch Name
Contact Person
Address
Contact number
* * *
Branch Name 2
Contact Person 2
Address 2
Contact number 2
I have used custom post UI plugin and another one that lets me add this data in the backend. I can't for the life of me figure out how to display it in the frontend.
I don't want it to act like a post where it lists everything and you click on it for more detail. It should just display as above when you click on a region from the dropdown. Is there a plugin that would do this or do you have to hard code it? | You can do that easy on this way, just duplicate `single.php` and rename to `single-custom-post-type-name.php` like `single-cars.php`, same thing with archive or taxonomy, `taxonomy-taxonomy-name.php` or `archive-taxonomy-name.php`
Or you can make your query for random page, home or blog:
<?php
// The Query
$query = new WP_Query(array('post_type' => 'your-custom-post'));
query_posts( $query );
// The Loop
while ( $query->have_posts() ) : $query->the_post();
// your post content ( title, excerpt, thumb....)
endwhile;
// Reset Query
wp_reset_query();
?>
Good luck! ;) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
Stop Custom post type from being searched via URL
I am developing a website in WordPress and I have used a custom post type for people to use. The custom post type only shows if the user is logged in and is the author of it, this shows on the profile page and nowhere else.
What I want to do is stop people being able to search for it in the address bar, for example..
< \- This will show the single version of this post, however I need it to redirect to the login page.
< \- This shows an archive page of the custom post type, however I need this to redirect to the login page. I have solved this temporaroly with a 301 redirect, however if you have any other advice, I would appreciate it.
Any help would be great! | You could use `template_redirect` hook to redirect your pages, like this:
function my_page_template_redirect() {
global $wp_query;
$object = $wp_query->get_queried_object();
//this returns queried object. Check the conditions and redirect
}
add_action('template_redirect', 'my_page_template_redirect'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, urls, archives, custom post type archives"
} |
Why this thumbnail hard crop code does not work?
I am trying to show thumbnail image as an attachment in the feed. So I use following code.
function add_images_to_rss($var) {
global $post;
if(has_post_thumbnail($post->ID)) {
$tid = get_post_thumbnail_id( $post->ID);
//$thumb = wp_get_attachment_image_src($tid, 'large');
$thumb = wp_get_attachment_image_src($tid, '100x100');
$thumb_meta = wp_get_attachment_metadata($tid);
$up = wp_upload_dir();
print '<enclosure type="'.get_post_mime_type($tid).'" length="'.filesize($up['basedir'].'/'.$thumb_meta['file']).'" url="'.$thumb[0].'" />';
}
}
add_action('rss2_item','add_images_to_rss');
But it shows larger size images as attachment. It suppose to show 100x100 size attachments only. What I am doing wrong ?
How can I show 100x100 image size attachemnts in that feed?
site is : < | You are using the size parameter of `wp_get_attachment_image_src` in a wrong format. This parameter can be:
* A string: keyword of the image size; thumbnail, medium, large, full or any other custom size previously registered).
* A 2-items array representing the width and height; for example, `array( 100, 100 )`.
So, you have to change this:
$thumb = wp_get_attachment_image_src($tid, '100x100');
With:
$thumb = wp_get_attachment_image_src( $tid, array(100,100) );
And this should also work for thumbnail size:
$thumb = wp_get_attachment_image_src( $tid, 'thumbnail' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rss, thumbnails, images"
} |
Remove link from post images
When Upload images from Editor and publish the post, I see for all images have link. How can remove it | This should do the trick. The filter will check for images and removes the a (link) tag. Just add it to your theme's functions.php:
add_filter( 'the_content', 'attachment_image_link_remove_filter' );
function attachment_image_link_remove_filter( $content ) {
$content =
preg_replace(
array('{<a(.*?)(wp-att|wp-content/uploads)[^>]*><img}',
'{ wp-image-[0-9]*" /></a>}'),
array('<img','" />'),
$content
);
return $content;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post thumbnails"
} |
Is there a way to display a menu using the ol tag instead of the default ul tag?
I'm trying to display a menu using `wp_nav_menu()`. The default markup that the function generates is a menu parented by a `<ul>` tag like so:
<ul>
<li><a>Menu 1</a></li>
<li><a>Menu 2</a></li>
<li><a>Menu 3</a></li>
</ul>
My question is, is there a way to display a menu using the `<ol>` tag instead of the default `<ul>` tag? | You can make use of the `items_wrap` parameter to achieve this. For example like this:
'items_wrap' => '<ol id="%1$s" class="%2$s">%3$s</ol>'
More information at codex: `wp_nav_menu`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "template tags"
} |
Template for product-category page
Where can I find the template that is used for the product-category page? The general template is "page-full.php". But where is the template for the single-product page (single.php?) and the product-category page? I'd like to edit them to show elements that are not visible on other pages and vice versa. Much appreciated. | Your theme doesn't necessarily include all these template files.
It might just use `index.php` to serve the single page template as well as listings (category, date, author, tag, etc).
The articles Theme Development and Template Hierarchy from the codex should get you on the right road with theme development.
If you add a `single.php` file, WP will use that instead of `index.php` for example.
'product-category.php' (as @ialocin rightly says) is almost certainly a WooCommerce template file and the way you override that is different. They have good docs: <
The general principle is the same - you override the default template (index.php) with successively more-specific templates. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, templates, page template, woocommerce offtopic"
} |
multiple orderby in pre_get_posts action
I used to be able to sort query results by 2 criteria ("sort results first by status=unsold ASC then by date DESC) like this:
add_action( 'pre_get_posts', 'my_get_posts' );
function my_get_posts( $query )
{
if (is_admin()){
return;
}
if (is_post_type_archive('objet')){
// Stock: sort by unsold first, then by date
$query->set('meta_key', 'wpcf-object-sold-status' );
$query->set('orderby', 'meta_value date');
$query->set('order', 'ASC DESC' );
}
return $query;
}
But now, it does not change the result order anymore. I have no idea why it stopped functioning. Maybe the update from Wordpress 3 to 4? | As Milo said :
$query->set('meta_key', 'wpcf-object-sold-status' );
$query->set('orderby', array('meta_value' => 'ASC', 'date' => 'DESC'));
// $query->set('order', 'ASC DESC' ); // not needed
Relevant link: < | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 8,
"tags": "order, pre get posts"
} |
Stylesheet comment header: Which header names are mandatory?
I've always used the same comment header names in my style.css document. Theme Name, Theme URI, Author etc. For example:
/*
Theme Name: Example
Theme URI:
Author: John Doe
Author URI:
Description: An example.
Version: 1.0.0
Tags: tags
*/
Which of these lines are _mandatory_? | Technically speaking all you need is the `Theme Name` in your stylesheet header. This will identify your theme. All the other info is need-to-know info and can be omitted.
If your theme is a child theme, you will need to have `Template` as well as this will be the path to the parent theme. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "templates, css"
} |
Redirect not logged in users if they are on a specific page and category
Following code is working fine for pages but how to add category id as well with pages in the following code.
add_action( 'template_redirect', function() {
if ( is_user_logged_in() || ! is_page() ) return;
$restricted = array( 250, 253 ); // all your restricted pages
if ( in_array( get_queried_object_id(), $restricted ) ) {
wp_redirect( site_url( '/user-registration' ) );
exit();
}
}); | In you actual code you can see this:
if ( is_user_logged_in() || ! is_page() ) return;
This code does this: if user is logged in or **is not in a page** , then return/do nothing. You need to remove `! is_page()`:
add_action( 'template_redirect', function() {
if ( is_user_logged_in() ) return;
$restricted = array( 250, 253 ); // all your restricted pages
if ( in_array( get_queried_object_id(), $restricted ) ) {
wp_redirect( site_url( '/user-registration' ) );
exit();
}
});
Alternatively you can leave `is_page()` and add also the check for `is_category()` as your needs. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "template redirect"
} |
How to see list of plugins
Is there any tool out there for seeing a list of all the loaded plugins and how much time they took to load? Looking to analyze plugins effect on my site's performance. | # There are a lot of tools available
Below are my personal favourites
1. Pingdom
<
2. Google Pagespeed
<
3. GTMetrix
gtmetrix.com | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "plugins, performance, debug"
} |
How to display error on specific template?
I know in wp-config.php editing this line:
define('WP_DEBUG', true); - on display error
define('WP_DEBUG', false); - off display error
I just want only display error in specific template or page. | @PieterGoosen gave some good advice. Focus on that,
But if you really wan it, then you can set debug ON temporarily on your website this way. In your `wp-config.php` use this instead.
if ( isset( $_GET['debug'] ) && 'debug' == $_GET['debug'] ) {
define( 'WP_DEBUG', true );
}
Then access your website homepage/any page and add `?debug=debug` at the end of URL. For example if you have page `www.example.com/about/` then use this link to enable debug.
| stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "templates, wp config"
} |
Excert ( the_excerpt(); ) Not working properly
I am creating custom theme, I have included excerpt in the index file
<article class="post">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-info"><?php the_time('F j, Y g:i a'); ?> | by <a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>"><?php the_author(); ?></a></p>
<?php the_excerpt(); ?>
</article>
This will create result like this
!Fig 1
But when I click the heading of the post it will redirect to the post page correctly but **only 55 words are displaying** See below screen shot
!Fig 2 | If you adding this code in `content.php` then you should use conditions.
<?php if ( is_single() ) : ?>
<?php the_content(); ?>
<?php else : ?>
<?php the_excerpt(); ?>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, excerpt, blog"
} |
Hide menu items if the page content is empty
i am looking for solution to hide (just not print) menu items if the page content is empty.
by default wordpress create menu item when new page created. and that ok.
but what i don't want, is when new page created, and the user still did not add any content to the page, is to show the page in the menu.
any suggestions? | You could try this, loop through all the `wp_nav_menu` items, get the post using the Object ID then test to see IF the content is empty. **IF** that content is empty then unset it from the items array:
function remove_empty_items( $items ) {
$blog_page = get_option( 'page_for_posts' );
$home_page = get_option( 'page_on_front' );
$postArr = get_posts ( 'post_type=post' );
foreach( $items as $key => $item ) {
$tmpPost = get_post( $item->object_id );
if( $item->object_id == $blog_page && empty( $postArr ) ) {
unset( $items[$key] );
} else if( $item->object_id !== $home_page && empty( $tmpPost->post_content ) ) {
unset( $items[$key] );
}
}
return $items;
}
add_filter( 'wp_get_nav_menu_items', 'remove_empty_items' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "menus"
} |
How to put the site map to every post?
The site map is like this:
Menu_A >> Sub_menu_b >> Post
It appears in every forum. How can I put this to the top of every post?
I admit that this question is so easy, and I have searched for it but can't find what I want. I have tried using these keyword: _site map, site navigation, site direction_ and _site address_ but find no help. | You're looking for **breadcrumbs** , not a site map. There are plenty of plugins in the WordPress repository that might suit your purpose: `breadcrumbs` plugins. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sitemap"
} |
Plugin Development - Get Admin Url (Including cases where wp-admin is not used)
I'm currently writing a WordPress plugin, and am looking to retrieve the WordPress admin url. It sounds simple enough - and it is - assuming every WordPress install is using the default `wp-admin` slug; I could simply call `get_admin_url()`, which is a wrapper for `get_site_url()`, with `wp-admin` hard-coded (see here: <
However, I don't want to work under an assumption that this url will never change. I'd like to be able to retrieve the url regardless of whether it's default or not; i.e. for either of these cases:
One suggestion has been to allow the plugin user to define the admin url slug, should it be different from the default, but it would be better if there were some way to retrieve it without forcing the user to specify. I'd really appreciate any help on this. | That's why the last line of the `get_admin_url` contains the line:
return apply_filters( 'admin_url', $url, $path, $blog_id );
Any valid modification of the admin URL will be via that filter, so `get_admin_url` is the correct function to use in all cases. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, admin, url rewriting, wp admin, site url"
} |
Is resetting post data necessary with custom WP_CLI commands?
Is it strictly necessary to call `wp_reset_postdata();` in a WP CLI command? I am doing it out of habit but just wondered if the `$post` object needed to be reset. | I did a little digging and found that the answer varies depending on your situation but for the most part no. If you are using the global $post variable outside a query then maybe. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp cli, wp reset postdata"
} |
Custom link text wp_get_archive link
Im trying to create custom text for the archive links in my sidebar. Right now it prints it but it comes out as regular text - i'm trying to make the full text output into the link.
so "+ Trip {archive-link}" should be the link text
<?php wp_get_archives( array( 'type' => 'yearly', 'before' => '<li class="CAPS source-bold"><span class="plus">+</span> Trip ','after' => '</li>', 'format' => 'custom', ) ); ?>
any help would be greatly appreciated! | I think the simplest way would be to use the get_archives_link filter. For example:
add_filter ('get_archives_link',
function ($link_html, $url, $text, $format, $before, $after) {
if ('with_plus' == $format) {
$link_html = "<li class='CAPS source-bold'><a href='$url'>"
. "<span class='plus'>+</span> Trip $text"
. '</a></li>';
}
return $link_html;
}, 10, 6);
Then, in your template:
`<?php wp_get_archives (['type' => 'yearly', 'format' => 'with_plus']) ?>` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp get archives"
} |
Ajax resetting my global variable
I am wondering why I can't read the updated value of `$_TEST`. It seems that `$_TEST` is being reset with each Ajax call.
// functions.php
$_TEST = 0; // the variable I want to update with each Ajax call
if ( is_admin() ) {
add_action( 'wp_ajax_get_global_val', 'get_global_val');
add_action( 'wp_ajax_nopriv_get_global_val', 'get_global_val');
}
function get_global_val() // my Ajax function
{
global $_TEST; // the value I want to update
echo $_TEST; // displaying 0 instead of 1
$_TEST = 1; // update my variable
} | Each time you're making an ajax call, `$_TEST = 0;` is being evaluated again. You use the options API to manipulate your variable.
function get_global_val()
{
$count = get_option( 'mycount' );
$count++; //or whatever you want to do with it
update_option( 'mycount', $count );
die("New value is $count");
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions, ajax"
} |
Wordpress portfolio pagination on home page
I am new to wordpress i am trying to add pagination to my home page that shows portfolios, example there are total of 80 portfolios when i open my site it automatically shows all 80 portfolios on home page ,is there any way that i can add **pagination** or **load more** kind thing on my home page .how to to do that have a look at what it is like now view here | You can set the amount of posts to display in the admin panel under 'Settings > Reading > Blog pages show at most .. posts'.
If you want to style this afterwards, more information here: < Or a useful plugin: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins, php, ajax"
} |
How to configure CNAMES to be part of a WordPress Network
Is it possible to have a network setup based on CNAME? I know that WordPress networks handle sub-directory structures in the a network quite nicely, but I am wondering if I can do the same with with CNAMES.
For example, can I set one of my WP networks to house these 2 sites (thus giving me the ability to share plugins and themes):
* www.example.com
* dev.example.com | Correct me if I'm wrong, but I believe you are mixing up the terms of CNAMES and subdomains a bit.
In case you are looking for a subdomain setup for WordPress Multisite: Yes this is possible:
> The sites in a network have different URLs. You can choose one of two ways for the URL to specify the site:
>
> -Each site has a different _subdomain_. For example: `site1.example.com, site2.example.com`.
>
> -Each site has a different _path_. For example: `example.com/site1, example.com/site2` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, subdomains, network admin"
} |
Number of posts in page - set per category and exclude sidebar
I have a widget in the sidebar that shows recent posts. The code below works to set the number of posts per page in each category, but it also affects the sidebar. Is there any way to exclude the sidebar?
/** Different number of posts per page depending on the category **/
function hwl_home_pagesize( $query )
{
if ( is_category( 'video' ) )
{
// If you want "showposts"
$query->query_vars['showposts'] = 10;
return;
}
}
add_action( 'pre_get_posts', 'hwl_home_pagesize', 1 ); | Check for `is_main_query` on the query object.
if ( is_category( 'video' ) && $query->is_main_query() ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
FORCE_SSL_ADMIN not working
Any ideas why `define('FORCE_SSL_ADMIN', true);` wouldn't work?
I'm not getting any errors at all, but a `http` request to `example.com/wp-admin` isn't redirecting to `https` | Just figured it out... It was the positioning of the define statement.
I added the below above the `/* That's all, stop editing! Happy blogging. */` line
define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
Thanks! | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp admin, security, wp login form, ssl"
} |
How to HTML5 FormData Ajax
How do I use FormData in wordpress ajax ? I am appending files and strings to formdata.
var formdata = new FormData();
formdata.append('name', 'This is Name')
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
data: {'action':'plugin_save', 'data':formdata},
contentType:false,
processData:false,
success: success,
error: error
});
// php
sends 0 ? | The action should be part of the data object:
var formdata = new FormData();
formdata.append('name', 'This is Name');
formdata.append('action', 'plugin_save');
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
data: formdata,
contentType:false,
processData:false,
success: success,
error: error
}); | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 5,
"tags": "ajax, javascript, forms"
} |
Wp Query custom search by meta query
The post meta name of a post is "Klevis V. Miho". Now when searching for:
"Klevis Miho" => Nothing displays
Is it possible to show results with that search string?
Below is what I am up to now:
$args['meta_query'][] = array(
'key' => 'name',
'value' => $name,
'compare' => 'LIKE'
); | I did it this way:
$name = explode(' ', $name);
foreach($name as $string) {
$args['meta_query'][] = array(
'key' => 'name',
'value' => $string,
'compare' => 'LIKE'
);
}
Which works good, but I'm not sure if that's the best solution. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "meta query"
} |
WordPress HTML5 Gallery Support - Convert HTML4 -> HTML5
As of WordPress 3.9, WordPress generates HTML5 Galleries if HTML5 is supported in the theme:
`add_theme_support( 'html5' );`
Originally in my theme development I did not declare HTML5 support and I've already published a few galleries which are using the old `DT` / `DL` HTML. Now I have declared HTML5 theme support as shown above, but WordPress won't regenerate my gallery even after saving the page or publishing a new gallery.
How do I "trick" WordPress or have WordPress start generating HTML5 galleries after my theme has been activate / activated? | Try this:
add_theme_support( 'html5', array( 'gallery', 'caption' ) );
And don't forget to declare the HTML5 DOCTYPE at the very beginning of `header.php` with:
<!DOCTYPE html> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, gallery, html5, add theme support"
} |
Search taxonomy terms, not posts
I want to generate a list of Custom Taxonomy terms, searching through the searchform. I don't need to return posts associated the the term, I want to return the terms themselves that will link to get_term_link()
thanks | Use get_terms() to retrieve terms that match your search query like :
$termsResult = get_terms( 'CUSTOM_TAXONOMY_NAME', 'search=SEARCH_QUERY' );
where,
**CUSTOM_TAXONOMY_NAME** is your custom taxonomy and **SEARCH_QUERY** is the string which you are using to search for terms.
Afterwards you can generate list like :
if ( ! empty( $termsResult ) && ! is_wp_error( $termsResult ) ){
echo '<ul>';
foreach ( $termsResult as $term ) {
echo '<li><a href="'.get_term_link( $term ).'">' . $term->name . '</a></li>';
}
echo '</ul>';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "search"
} |
How to edit wordpress pages through cpanel?
Can you visit < in firefox ? The links are overlapping there. What to do ? If core pages or theme need to be edited, where to find the pages ? The stylesheet is contained in wp-content | your provided link there is mistake in your uploaded product images.There is no image in all post/product that's why links are overlapping.
For that whenever you add this all posts/product into wp-admin at that place please select or upload appropriate images or remove this tag from the specific file. file location is below.
wp-content->themes->your-theme->content.php or in template folder your-template.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
Disable Jetpack Publicize for blog but keep for custom post type
I have a WordPress site with a blog and also a custom post type (set up with Pods) called extra. I want the extra custom post type to be auto published to a Facebook page and the blog to just publish to the site.
I have set up Jetpack Publicize, and by default it publishes the blog (post) to Facebook but not a custom post type. By adding the snippet below in functions.php, Publicize publishes the custom post type to Facebook.
add_action('init', 'my_custom_init');
function my_custom_init() {
add_post_type_support( 'extra', 'publicize' );
}
How do I get publicize to not publish the blog is my question? I tried remove_post_type_support like so:
add_action('init', 'my_custom_init');
function my_custom_init() {
remove_post_type_support( 'post', 'publicize' );
add_post_type_support( 'extra', 'publicize' );
}
but did not work. | From Jeremy Herve:
"Posts support Publicize by default, so I'm afraid you won't be able to completely remove Publicize from the post screen.
I took note of your suggestion though, and we'll consider adding a filter to disable Publicize for posts in a future update." | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "facebook, plugin jetpack"
} |
Change the main width of Twenty Thirteen theme
I would like to reduce the main width (including the header) of my Twenty Thirteen website, and change the color of the outside (in sort, something similar to the Twenty Twelve theme: <
Thank you in advance for any help. | Try adding the following to your custom css, with 960px being your desired width.
.site {
max-width: 960px;
}
And for the background color:
.body {
background: #f7f7f7;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, theme twenty thirteen"
} |
ACF if / else checkbox
Hi I've got this code that's looking to see if a checkbox is ticked in a custom post type and then displaying the relevant link
<?php
if(in_array("Yes", get_field('news__item--external') )){
?>
<a href="<?php echo the_field('news__item--external-url'); ?>" class="more icon--chev">View full article</a>
<?
}
?>
I want to add an else statement to it to provide a different result if no link. Doing this:
<?php
if(in_array("Yes", get_field('news__item--external') )){
?>
<a href="<?php echo the_field('news__item--external-url'); ?>" class="more icon--chev">View full article</a>
<?
} else {
<a href="home.php">Home</a>
}
?>
Gives me a parse error. How can I include the else statment?
Thanks | Small fix for you :)
<?php
if( in_array( "Yes", get_field( 'news__item--external' ) ) ) {
?>
<a href="<?php echo the_field('news__item--external-url'); ?>" class="more icon--chev">View full article</a>
<? } else { ?>
<a href="home.php">Home</a>
<?php } ?>
The code to fix was:
<php } else { <a href="home.php">Home</a> } ?>
You was missing the end php tag from the { after else then the opening php tag before the a tag. Final bit was open php tag after the a tag. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "advanced custom fields"
} |
Can't edit Custom Post Type slug/permalink
I have a custom post type and the permalink shows up but I am unable to modify it like I can with Pages and Posts. Is there a way to enable this? I have a few conflicts with some pages and I'd like to fix them but I can't. Any ideas? | Found a box under Screen Options to display the Slug on the custom post type. Created a metabox with the slug to be edited, not quite how it works on Pages but it solved the issue. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom post types, permalinks, slug"
} |
Display based on specific user
I'm struggling to work this out, but can anyone help me on how to write a statement to display a line of text IF the author of a post is equal to a specific USERID?
So for example
**IF THE CURRENT POST**
**IS WRITTEN BY A SPECIFIC USER ID**
**THEN DISPLAY SOME TEXT** | Have you considered using the get_the_author_meta() function? It would look something like this:
if (get_the_author_meta('ID') == ID_YOU_ARE_TESTING_FOR) {
// display text
}
This would need to be used within the Loop. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user roles"
} |
Visual Composer integration
I've installed Visual Composer on my own template. The thing is that is not rendering all it's shortcodes.
<?php $post = get_post( $post->ID );
echo $post->post_content; ?>
Is that code wrong? Am I missing some includes or didn't run some functions? | Issue solved:
I had to `do_shortcode` to `post_content`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "shortcode, the content"
} |
The_content is different from category archive to other pages
I'm trying to use a plug-in that is adding bookmark button to the posts.
It's working well except in the category archive page:
I can't figure out why `the_content()` on page, post and archives (tags, authors, and even search result) has the plugin div inside.. correctly.
But in the category archives there is not.
Any idea? | I have found the solution. In the plugin file class-binnash-wpbookmark.php there is
if(is_category()) return $content;
I have just commented it and now I have the div at the top of The_Content() in the category archive page | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "the content"
} |
How to schedule categories?
Is there anyway to schedule categories? like I already created the categories but I don't want it published to the public until the scheduled date like how you can schedule posts. | You could schedule a function to be called using a cron job. <
When you're done, you could probably unregister the cron job from inside the function so it isn't called repeatedly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, taxonomy, scheduled posts"
} |
Custom php file in wordpress
For some purposes i want to have custom php file in my Wordpress that will output content from 3 plugins.
This is the PHP code in the file :
<div class="wrap">
<div class="sidebar1">
<?php dynamic_sidebar('sidebar1'); ?>
</div>
<div class="sidebar2">
<?php get_template_part('sidebar2'); ?>
</div>
<div class="sidebar3">
<?php dynamic_sidebar('sidebar3'); ?>
</div>
However, when i try to open / execute the file i get error like
Fatal error: Call to undefined function dynamic_sidebar() ...
i guess its because i have to include some files to make all the functions / classes available to the custom PHP file.
How can i run this file without errors ? | Andrew Bartel is on the right path, but the link doesn't quite do what you want.
For static PHP files to access WordPress core functionality you need to add this to the top of the PHP file:
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
(This code is from index.php in WordPress core)
Ideally though, you would want to create a WordPress Page Template in your theme or child theme with the custom PHP code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "customization, templates"
} |
How to change "You must be logged in to post a comment."
Some of my users have mentioned that my site is confusing for them. As this is the case, I would like to actually make links to Login/Register for my unregistered visitors to quickly do so if they would like to leave a comment.
Right now it just says "You must be logged in to post a comment." with no link to Login. Where can I edit this and change it to "You must Register or Login to post a comment." with links to them? | You can try to modify it with the `comment_form_defaults` filter:
/**
* Modify the "must_log_in" string of the comment form.
*
* @see
*/
add_filter( 'comment_form_defaults', function( $fields ) {
$fields['must_log_in'] = sprintf(
__( '<p class="must-log-in">
You must <a href="%s">Register</a> or
<a href="%s">Login</a> to post a comment.</p>'
),
wp_registration_url(),
wp_login_url( apply_filters( 'the_permalink', get_permalink() ) )
);
return $fields;
});
where we use the `wp_registration_url()` and `wp_login_url()` core functions.
_ps: theinfo on the `comment_form_defaults` filter seems to be missing from the Codex._ | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 9,
"tags": "comments, login, user registration"
} |
Displaying Content with WP Rest API
I have been spending some time working with the new Rest API. I understand what it is doing but I don't understand how the JSON is used to actually display the content on a page.
I have been fooling around with example.com/wp-json/posts and I see all the code. I can even figure out how to filter them the way I want. What I can't seem to figure out is how do i display this content in a WP post or page?
example: I am using a multisite install and I would like to use 5 of the most recent posts from SITE A on SITE B but I don't understand how all that JSON code is edited and displayed.
I can't seem to find any beginning to end samples on this subject everyone just shows how you grab the content. | I will assume you want to use PHP to display this data directly using a template, there are alternatives such as using another language or actually creating posts via the API.
Simply put you want to take the JSON string and convert it into a PHP object or array using `json_decode`. <
Once the JSON is stored as an object or array you would simply echo or do what you want with the data.
For example:
$json = '{"a":hello,"b":hi,"c":hey,"d":yo,"e":ola}';
$data = json_decode($json);
echo $data->{'a'}
// this should echo the value "hello"
It's important to note to cache external requests, you do not want to make a remote request each time the data is needed, rather you would use the Transient API with a set time for the data to expire and refresh.
Two other important links:
<
< | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "api, json"
} |
How to count number of records found in a database table?
I am new to wordpress development & tried to learning plugin development.I have created a custom table from which i want to show the number of records found.I have tried the below code but it always shows 1 as a result irrespective of number of rows in a table.
//To show number of rows in table
function DB_Tables_Rows()
{
global $wpdb;
$table_name = $wpdb->prefix . 'mydata';
$count_query = "select count(*) from $table_name";
$num = $wpdb->get_var($count_query);
$num = $wpdb->num_rows;
echo $wpdb->num_rows . 'Rows Found';
} | Why don't you directly echo the $num as it will contain the count of rows already...Here's the edited part..
//To show number of rows in table
function DB_Tables_Rows()
{
global $wpdb;
$table_name = $wpdb->prefix . 'mydata';
$count_query = "select count(*) from $table_name";
$num = $wpdb->get_var($count_query);
echo $num . 'Rows Found';
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "plugins, wp query, database"
} |
Accidentally changed the permalink structure
I've changed the permalink setup on our webpage and now none of the links to the blogs are working. To be honest, I didn't really need to do it, but I was really trying to add a bit more of a description to my url and obviously have done the wrong things.
Is there anyway I can fix this? It just loads the error 401 or it say page not found
Any assistance would be greatly appreciated | Please check the permission for your .htaccess file in your WordPress root and if you are allowed to edit the file then you can just paste the code that you get from setting the permalink structure. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, 404 error"
} |
Change a custom post type on an existing site
I have a site using two custom post types called destination and walk, where destination is used to categorise walks, by pulling a list of destinations into the walk editor.
Part of the site has now been spun out into it own site dealing with cycling holidays exclusively, but the walk slug is still present in the urls, which is obviously inappropriate.
Does anyone know if and how I can change the url slug for the custom post type without completely busting 90% of the links on the site?
Cheers | Yes, you can change the url slug by searching for the custom post type where it is created i.e register_post_type and change the slug parameter value to whatever you like.You can follow the following steps..
Locate and replace post type slug with any slug you need, try not to use spaces.
1) Just search for slug you need to update.
The script should look like:
'slug' => 'walk'
2) Save the file and test your website.
3) Sometimes you may get 404 error after changing custom post type slug, it is related to permalinks issue. You need to open admin panel, change permalinks structure to default, save website and then revert it to previous state. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
Hide breadcrumbs on specific pages
Can anyone help me to hide breadcrumbs from certain page ID's?
I'm using the Breadcrumb NavXT plugin. I've only found out how to hide it from the home page.
I'm using this code in my `header.php`:
if ( ! is_front_page() ) {
bcn_display();
} | Suppose you have set up an array of page IDs where you don't want the breadcrumbs to be displayed.
$ids = array( 4, 8, 15, 16, 23, 42 );
Now you just have to check if the currently displayed page (or post) has one of these IDs, and if not, display the breadcrumbs.
if ( ! in_array( get_the_ID(), $ids ) ) {
bcn_display();
}
**// EDIT**
And if you want to exclude pages only--no other (custom) posts--you could speed up the check a bit.
if (
! is_page()
|| ! in_array( get_the_ID(), $ids )
) {
bcn_display();
}
**// EDIT** (as per your comment)
To exclude the front page as well as specific pages, try this:
$ids = array( 4, 8, 15, 16, 23, 42 );
// Automagically add the ID of your front page
$ids[ ] = (int) get_option( 'page_on_front' );
if (
! is_page()
|| ! in_array( get_the_ID(), $ids )
) {
bcn_display();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "conditional tags, breadcrumb"
} |
WP_Query - Object manipulation vs WordPress functions
Although this could be opinion based, there must be a some consistent way / optimised way of manipulating data from a `WP_Query`. For example, the 'best' way to get a posts title?
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$choice1 = get_the_title();
$choice2 = the_title();
$choice3 = $query->post->post_title;
}
}
I'm thinking due to consistency and reduction of function calls, the 3rd option may be a better choice (and a little more consistent since both the `if` and `while` statements use the object notation.)
The third option also gives much greater access to data over the limited number of WordPress functions. Are there any real drawbacks to using it? If not, why bother with the WordPress functions? Sanitation? Error catching? | All 3 of these _could_ do the same thing, it's just a matter of how you want to use them.
`the_title()` calls `get_the_title()` which gets the title by `$post->post_title`.
View `the_title()` Source on Trac
View `get_the_title()` Source on Trac
Personally, I would never use choice 3 as from a readability stand point it's not the most obvious what it's doing. On top of that as Milo points out, you do lose `the_title` filter which is found in `get_the_title()`:
`return apply_filters( 'the_title', $title, $id );`
Choice 1 / 2 are used in different scenarios. You can never assign `the_title()` ( without any parameters ) to a variable because by default it will echo out the title to the screen. The function `get_the_title()` is used to actually assign the title to a variable should you need to run any kind of manipulation on the post title.
You could use any of the choices to achieve the same result it just depends what you're trying to do. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query"
} |
Image filter works on attachement pages but not posts. I can't get the image ID
I'm using a plugin called Exifography. They provide the capability to use filters to adjust for your purposes. In the example provided I'm simply trying to get the height & width of the image and return it.
This works great on the attachment page (image.php) but will not work with posts. I can't figure out how to properly get the image ID in order to query the wp_get_attachment_metadata function.
This will be used on posts with multiple images.
function massage_exif($content,$postID,$imgID){
$imgmeta = wp_get_attachment_metadata($imgID);
$width= $imgmeta['image_meta']['width'];
$height = $imgmeta['image_meta']['height'];
array_push($content,$height . 'x' . $width);
return $content;
add_filter('exifography_display_exif','massage_exif');
Using ver 4.01 of WP | Well, after some discussion with the developer, I was missing some key items in the add_filter line. I needed to pass along the "11","3". The three is the important item here. It is the number of variables to passback... the 3rd being the elusive $imgID.
function massage_exif($content,$postID,$imgID){
$imgmeta = wp_get_attachment_metadata($imgID);
$width= $imgmeta['image_meta']['width'];
$height = $imgmeta['image_meta']['height'];
array_push($content,$height . 'x' . $width);
return $content;
add_filter('exifography_display_exif','massage_exif',11,3);
Thanks for helping me keep digging until and answer was found. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, filters"
} |
remove_action on after_setup_theme not working from child theme
I am trying to remove a theme action for an elegant-themes theme using a child theme.. This works when I remove action after add_action code anywhere in the parent theme functions.php. However, it does not work when I add it from child theme functions.php.
remove_action ('after_setup_theme', 'et_pb_setup_theme' , 10);
Remove action has same priority 10 as the add action. Shouldn't it work?
add_action( 'after_setup_theme', 'et_pb_setup_theme' ); //parent theme add_action | As @cybmeta already pointed out, you are too early with your removal. So you have to defer the actual removal, for instance like so:
add_action( 'after_setup_theme', 'wpdev_170663_remove_parent_theme_stuff', 0 );
function wpdev_170663_remove_parent_theme_stuff() {
remove_action( 'after_setup_theme', 'et_pb_setup_theme' );
} | stackexchange-wordpress | {
"answer_score": 29,
"question_score": 20,
"tags": "functions, themes, actions, child theme"
} |
Query all post types but limit to parents
I'm building a site with several post types and am using a single `index.php` to query the archive for each one in turn. One of these post types is hierarchical and I'd like to just query the parent. I can use `query_posts` to limit to `'post_parent' => 0` but that creates a new query and resets the post type argument meaning that I'd have to create separate queries for each post type.
Is there a way to limit `while ( have_posts() ) : the_post();` to parents only without creating a new query? | In your functions.php you can create a function that will hook into the pre_get_posts hook. Something like (just an example):
function alter_query($query){
$query->set('post_parent', 0);
}
add_action( 'pre_get_posts', 'alter_query' );
There you can alter the main query. That way while(have_posts()) : the_post(); will still just normally work. (You should check if you are altering the right query and such. Otherwise the post_parent will be applied to all query's by wordpress. You don't want that).
The BIG advantage is, that if you alter the main query, you only have to do that. Wordpress will still select the appriopiate template and such. If you also want to alter the template loaded, you can use the template_redirect hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, loop, query posts, hierarchical"
} |
Display Child Page with custom fields within Parent Page
I have a parent page with multiple Child Pages.
On the child page template I have an include which has customfields. This works perfectly. The custom fields are on the child page in wordpress.
The custom fields are all within page-customfield-3.php and included in page.php to display them.
I included page-customfield-3.php within page-parent.php and it does not display the custom fields. I have included a link to a github gist with the code for each file as it is very long otherwise.
CURRENTLY WORKING
Page.php
|
Page-customfield-3.php
CURRENTLY NOT WORKING
Page-parent.php
|
Page-customfield-3.php
< | Your problem is that you are putting the page result in $page. While the normal commands like the_title() and get_field() will look for the $post variable if you are not setting a seperate ID of which you want the title.
I once did this by creating a backup of the $post variable, and then just put each post i wanted to include on the parent page in the $post variable. Then included the .php files, and every normal command like the_title(); & get_field(); works like it would normally would. But this is dirty, and there is probably a much better way to accomplish this.
You should probably just replace the main query with your get_posts query. Afterwards you should reset & restore the wp_query.
An other option would be to alter the page-customfield-3.php to include the $page variable you are setting in your page-parent.php. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, page template, advanced custom fields, child pages"
} |
get custom image size
In a post I want to place a custom image. how do i place a thumbnail with link to original image? below is my current code.
<a href="[site_url]/wp-content/uploads/GABON-Leopard-Gas-Discovery-1x1.jpg"><img class="alignright size-medium wp-image-5435" src="[site_url]/wp-content/uploads/GABON-Leopard-Gas-Discovery-1x1-200x112.jpg" alt="GABON-Leopard-Gas-Discovery-1x1" width="288" height="288" /></a>
I had to manually put in `-200x112` . is there any easier way to do this? | If you know the image's ID :
wp_get_attachment_image( $image->ID, array(200, 112) );
returns an HTML img element or empty string on failure. The entire code could be something like :
<a href="<?= get_attachment_link( '5435' ); ?>">
<?= wp_get_attachment_image( '5435', array(200, 112) ); ?>
</a> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "posts, images"
} |
If No Search Results, Show Posts from Alternate Search Query
I have a pretty standard loop which outputs "Sorry, No Posts Found" when a search result comes up empty.
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part ( 'templates/post', 'main' );
endwhile; else:
echo 'Sorry, No Posts Found';
endif;
How can I show alternate posts below that message?
So if someone searches for "Tacos" and no posts are found, the results page would say:
Sorry, No Posts Found. But here's some posts about Pizza... | I've never seen it done before but the logic of the PHP IF/ELSE should mean you could simply plug a new query in after the `ELSE:`
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part ( 'templates/post', 'main' );
endwhile;
else:
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
$the_query->the_post();
endwhile;
endif;
endif;
This is untested on my end. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "loop, query, search"
} |
Why is variable that get_post_meta stored in empty?
I have used the following bit of code in another script on the same site, & it worked there.
$this_post_id = get_the_ID();
$key_2_value = get_post_meta( $this_post_id, 'custom_select', true );
if( ! empty( $key_2_value )) {
echo $key_2_value ;
;}
var_dump($key_2_value)
`var_dump` outputs `string '' (length=0)`
I am trying to use it in a script called events-list.php. Events-list.php provides a short list of the events (which are posts) .
The meta field is definitely called `custom_select` | The variable that `get_post_meta` was stored in was empty because I wasn't getting an `id`. I was trying to use this code on a category page, not a single event. Without an `id` it couldn't identify the `post_meta` to use. So I corrected it with the following:
$latest_cpt = get_posts("post_type=event&numberposts=1");
$theidone =$latest_cpt[0]->ID;
$this_post_id = $theidone; //get_the_ID();
$key_2_value = get_post_meta( $this_post_id, 'custom_select', true );
if( ! empty( $key_2_value )) {
$thisisworking = $key_2_value ; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post meta"
} |
change width of the fullscreen editor
I'm using wordpress 4 and want the fullscreen page editor to be just as wide as the text of my page. eg 1024px.
I tried setting #wp-fullscreen-wrap in my css and the dfw_width option but they all seem to be ignored. | You probably mean the Distraction Free Writing mode. Am I right? Then you changed wrong ID, it's **#wp-content-editor-container** what you want to edit. But every time you hack WordPress core, a kitten dies. So if you like kittens, here is no-offensive solution for you. Put this code into **functions.php** file in your theme:
<?php
add_filter( 'admin_footer', 'fulleditorwidth', 99 );
function fulleditorwidth() {
?>
<style type="text/css">
#wp-content-editor-container { width: 1024px!important }
</style>
<?php } ?>
I recommend to add also **max-width: 100%** for responsive view.
Don’t hack your WordPress core files. If your wordpress will be updated, your changes will be overwritten. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "editor"
} |
Rename Index.php
I Renamed the index.php wordpress to index3.php, because i dont want offline the current site, that also has index.php as name and other CMS platform. But when I click on the internal links as "Services" he takes to the site current site.
Have something that I can set to go to the correct page and after then rename it to index.php when I want go online the new site?
Link: <
Thank you | Just move your wordpress installation to a subdirectory and switch back after.
See the Wordpress Documentation. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
Certain functions are undefined when called form mu-plugins
I have a correctly formatted php functions file in my mu-plugins/ directory. When trying to use wp_is_mobile() or current_user_can(), I get an undefined function error.
Fatal error: Call to undefined function wp_is_mobile() in /var/www/dev.example.com/public/wp-content/mu-plugins/multisite-functions.php on line 147
Are certain core functions defined after the mu-plugins? How do I fix or avoid this? Can I simply not use certain functions in mu plugins?
Thank you! | Thanks to diggy from StackOverflow I've foudn that in the WordPress cycle, the file vars.php (containing my needed functions) is included after muplugins_loaded executes.
Including wp_is_mobile() and current_user_can() in wrapper functions fixed my problem.
**CORRECT**
function my_epic_function() {
if(current_user_can( 'edit_posts' )) {
if(!wp_is_mobile()) {
//code to be executed
}
}
}
add_action('init', 'my_epic_function');
**INCORRECT**
function my_epic_function() {
//code to be executed
}
if(current_user_can( 'edit_posts' )) {
if(!wp_is_mobile()) {
add_action('init', 'my_epic_function');
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, plugin development, multisite, mu plugins"
} |
unexpected T_FUNCTION in plugin template
I have a plugin I have developed for a client which works fun on my server but doesn't work on theirs, they are on godaddy so I am guessing it's an issue with their PHP version?
add_filter('template_include', function ( $template ) {
if(is_tax('hha_cats')){
$template = dirname( __FILE__ ) . '/templates/category-hhavideo.php';
}
if( is_post_type_archive( 'hhavideo' ) ){
$template = dirname( __FILE__ ) . '/templates/archive-hhavideo.php';
}
return $template;
}, PHP_INT_MAX, 2 );
This code was written by another SE user after I was having another issue (here), is there a way to make this work with older versions of PHP? (Without checking, I believe her server is 5.2 and mine is 5.3). | **EDIT**
Undeleted my answer as the code seems to have helped the OP. Originally got beaten by @TomJNowell, so some content might be the same
**ORIGINAL ANSWER**
This is more PHP related than Wordpress. Anonymous functions, the syntax used in the code given, was only introduced in PHP 5.3 and will not work in older versions. If you are sure that your client is using PHP 5.2, it is most probably the reason for the error.
You can just make a slight modification to the code to get it to work on older versions
add_filter('template_include', 'my_function_name', PHP_INT_MAX, 2 );
function my_function_name( $template ) {
if(is_tax('hha_cats')){
$template = dirname( __FILE__ ) . '/templates/category-hhavideo.php';
}
if( is_post_type_archive( 'hhavideo' ) ){
$template = dirname( __FILE__ ) . '/templates/archive-hhavideo.php';
}
return $template;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "template include"
} |
Send attachments via wp_mail from temporary folder
Is it possible to send attachment via `wp_mail`, using temporary file, instad of uploading them to any actual folder on server?
For example:
<input type="file" name="file">
$attachment[] = $_FILES['file']['name'];
wp_mail(....,$attachment);
Documentation:
> The filenames in the $attachments attribute have to be filesystem paths.
How can i get the path for temporary file (if this is possible)? | Yes. it's possible. Attachment file contents are taken by wp_mail call.
Use `$_FILES['file']['tmp_name']` for filename | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "uploads, wp mail, input"
} |
Htaccess https 301 problem
Since 2 weeks I have installed an SSL certificate on my domain. I have changed my base urls to https so my canonical url is https now. But now I need to force to https. I did this with the below htaccess change, but if I update my permalinks in admin now, Wordpress overwrites it to the old htaccess and my https redirect is gone.
Has anyone any experience with this?
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) [R,L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress | You have to modify either before # BEGIN WordPress or after # END WordPress. This part is modified by WP, once you change your permanlink | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "permalinks, redirect, htaccess, https"
} |
How to get name of custom taxonomy
I need to get name of current custom taxonomy in archive.php file when page is showing posts belong to the one of custom taxonomy categories.
It's easy do it in WP loop but I need get it in front of loop's body.
How could I do it? | I believe you are talking about when the archive.php is used as a taxonomy page.
If so, you will first need to check if the current page being viewed is actually a taxonomy page. If you don't do this check, you will get errors on pages that are not taxonomy pages, for instance date archive and category archive pages if they all make use of the archive.php template. The reason is, the queried object varies from page to page, the queried object is diffirent for a taxonomy page than for a date archive page
So you would wrap your queried object inside a `is_tax()` conditional check to make sure that the taxonomy name only displays on the taxonomy page.
To get a complete overview of `get_queried_object()` on a page/template, simply do the following
<?php
$queried_object = get_queried_object();
var_dump( $queried_object );
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, loop"
} |
Correcting the content width when sidebar is inactive?
I want my website's content (posts) to be central in the page when the sidebar is inactive. I've currently got it set to fit both the content AND the sidebar on the same page. How can I make it correct itself if the sidebar is inactive?
I am using get_sidebar();
Here's my website that I'm referring to. | You could try something like this, within your sidebar.php file:
if ( ! is_active_sidebar ('SIDEBAR-NAME-OR-ID' ) ) {
echo '<style>.main-content { width: 960px; }</style>';
}
This is hackish, but it should work for what you're trying to do. There may be a better method but its hard to know without more context. The above code just spits out an inline style rule to full-width your .main-content wrapper _if_ no widgets are present in the sidebar. The wrapper currently is set to 620px in your stylesheet (why it's not full-width). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, sidebar, content"
} |
html5-reset theme does not show the image
I am started to create a custome theme based on the `HTML5-reset` theme that a downloaded from GitHub. before touching/modifying anything, just I tried to put an image under the `get_header();` and above the loop, using the following HTML code snipet:
<div class="the-image">
<img src="images/moonrise_100.jpg" alt="moonrise" />
</div>
but when I tried to see the result, unexpectedly showed nothing but the icon of broken-images, so inspected the element for any error or overriding using chrome but I can't find anything incorrect. What can be the origin of this. i checked everything, directory, name, image suffix and ... I use: xampp server. | Code is not readable in comment so I am adding it here. With a little explanation.
You will need to add full path of the image file to show them in theme. If your image is in theme directory then you will have to use theme directory path variable `bloginfo('stylesheet_directory')` with image name. So this is the code you will need to add in your theme files.
<div class="the-image">
<img src="<?php echo get_template_directory_uri(); ?>/images/moonrise_100.jpg" alt="moonrise" />
</div> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, themes"
} |
Problems using WP's oembed function + Instagram + AJAX
I am using a modal to load post content via AJAX. Inside the post's template I am using wp_oembed_get() to embed different types of media (YouTube, Vimeo, Flickr, and Instagram). Everything is working, except for Instagram.
When I open a post that contains an Instagram embed, it loads fine. But if I close the modal and try to load another post, the embed does not work correctly. The photo/video within the embed does not load.
This is the page: <
If you open one of the "Instagram Test" posts, close it, then load the other one, you will see what is happening.
I'm at the end of my rope in figuring this out! | Instagram has changed its embed code from being just an `iframe` to a bunch of HTML and a JS script. Very inelegant, but nothing we can do. This setup, of course, fails when called through AJAX since the JS file that's part of the HTML does not run. Thankfully there is another official way to make it work with AJAX in two steps:
1. Include this scripts in your HMTL:
`<script src="//platform.instagram.com/en_US/embeds.js"></script>`
2. Runs this JS after you load the content with AJAX:
`if ( typeof window.instgrm !== 'undefined' ) { window.instgrm.Embeds.process(); }`
What it does is, it looks for Instagram embeds and loads them. Best of luck! | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "oembed"
} |
Piklist File Upload
I am doing this tutorial: <
After creating this for a custom post type:
// Upload Image / File
piklist('field', array(
'type' => 'file'
,'field' => 'my_image'
,'label' => 'Upload image'
));
I then follwed by doing this
$image_ids = get_post_meta($post_id, 'my_image');
but now I am trying to call:
print_r($image_ids);
and no array gets output.
what am I doing wrong? How do I get the images uploaded in the custom postype? | hey try to use this i think it work fine
$image_ids = get_post_meta(get_the_ID(), 'my_image');
print_r($image_ids); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta"
} |
is_page_template returning false
I'm using woothemes Canvas with a child theme. Additionally, I am using the WP Listings plugin. I am creating a custom listings page template (overriding the plugin template) and I'm having issues recognizing the page type to include scripts/styles on that page type only.
Example:
if ( is_page_template( 'single-listing.php' ) ) {
add_action('wp_enqueue_scripts', 'your_function_name');
function your_function_name() {
the if statement is returning false, although it is using that file. | I think your problem is how your function is constructed and not your condition as such.
You should not be wrapping your function and your action in a condition like this. Page templates are selected really late in the query by the main query, and I probably think that this is way to late for your action to execute. By the time the condition hits true, the `wp_enqueue_scripts` hook already executed and cannot be rerun
If this is a single page, and that single page is for a custom post type called `listing`, you should be using `is_singular( 'listing' )` instead of `is_page_template()`
The correct way would be to wrap your scripts and styles inside your function inside your condition
You can try the following
add_action( 'wp_enqueue_scripts', 'your_function_name' );
function your_function_name() {
if( is_singular( 'listing' ) {
// add your scripts and styles
}
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "page template, child theme"
} |
Order by in foreach
hello im getting post_id by using wpdb after that i wanna show postmeta(sd_l2) order by their value
i uses this codes
global $wpdb
$top5_ov_performance = $wpdb->get_results("SELECT post_id FROM ".$wpdb->prefix."postmeta WHERE meta_key = 'sd_type' AND meta_value = 'desktop'");
foreach ($top5_ov_performance as $ov_perforamnce) {
$new_number = ($ov_perforamnce->meta_value / $mother_number) * 100;
echo '<div class="box">';
echo '<div style="width: '.$new_number.'%" class="fill">';
echo '<div class="fill-badge">'.get_the_title($ov_perforamnce->post_id).'</div>';
echo '</div>';
echo '<div class="empty">';
echo '<div class="empty-badge">'.get_post_meta($ov_perforamnce->post_id,'sd_l2',true).'</div>';
echo '</div>';
echo '</div>';
} | All you need to do is pass the field you want to order by in your SQL:
ORDER BY post_id DESC
This example will get the post_ids out with the highest first e.g. 99, 98, 97
OR
ORDER BY post_id ASC
will do it: 1, 2, 3 and so on.
Alternativly if you want to group the results by the meta_value:
GROUP BY meta_value | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, wpdb, post meta"
} |
Correct way to pass information between seperate shortcode functions
I contain all my short-codes in (the equivalent of) `functions.php`. I want to have one short-code function share information in an object, and another able to access that object. The shortcodes may or may not be on a page together.
I was thinking a unique `global $obj` rather than using `global $post`.
What is the 'correct' method in Wordpress? | The correct way is not to do it. Shortcodes are supposed to be self contained and represent an insertion point to some complicated HTML that is harder to get right or due to security permissions is impossible to insert in its pure HTML form.
Globals are hated magic when you write proper code, now think about plain text, how exactly the non technical writer can even guess that one shortcode is depending on the other, and what will be the result of removing one of them?
if the second shortcode needs to know the attributes passed to the first, just document that the user should pass the same parameters to both. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
Loading page content into a variable in template
On one of my custom templates, I need to do some work with the content before displaying it. Is there a way that I can load this content into a variable rather than just outputting it to the page?
This is what I've tried but it only outputs the page content, it doesn't load it into the variable.
$content = get_template_part( 'content', 'page'); | You can always use the output buffering to store the printing contents in a variable.
function return_get_template_part($slug, $name=null) {
ob_start();
get_template_part($slug, $name);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
$content = return_get_template_part('content', 'page');
This would be most preferable to keep using the get_template_part() right now. An alternative would be to use locate_template() function but it would compromise the use the default templates.
Check implementation of get_template_part() and locate_template() you would understand. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "page template, get template part"
} |
Link to external URL
Only information I found on this were hacks 6+ years ago or plugins. Quite simply, I want to grab a URL (www.google.com) from a custom post type and make a link that links to that URL.
Currently, my links just go to
> www.mysite.com/mypage/www.google.com
$url = get_post_meta(get_the_id(), 'ext_url', true);
return '<div">
<a href="' . $url . '">External</a>
</div>'; | Without ` in front, your code won't work. You will need to add that infront. You can make use of `parse_url` to add ` to urls that does not have that.
To make this protocol agnostic, you can simply use `//`
You can try something like this
$urlStr = 'www.google.com';
$parsed = parse_url($urlStr);
if ( empty( $parsed['scheme'] ) ) {
$urlStr = '//' . ltrim( $urlStr, '/' );
}
echo '<a href="' . $urlStr . '">External</a>'; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "permalinks"
} |
Admin Filter - Add Post Type Description on Post Type Page
WordPress allows adding `descriptions` to Custom Post Types whenever it's registered. ( `register_post_type()`. I would like to output that title on the Admin Landing Page ( View All _Post Type_ ) preferably underneath the title. I've looked into `/wp-admin/edit.php` but I'm not sure if the filter presented is usable in this case ( and thus it may not be possible to do ).
Line 274 on Trac is where it looks like the actual title gets set. Is is possible / is there a way to filter into it and add my post type description? | The filter `views_{$this->screen->id}` is fired just after the title of post edit screen has been print to screen, so it's a safe place to just echo what you want.
So you can simply do:
function post_type_desc( $views ){
$screen = get_current_screen();
$post_type = get_post_type_object($screen->post_type);
if ($post_type->description) {
printf('<h4>%s</h4>', esc_html($post_type->description)); // echo
}
return $views; // return original input unchanged
}
add_filter("views_edit-POST_TYPE_HERE", 'post_type_desc'); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "custom post types, wp admin, description"
} |
Page_link change
I'm trying to change default pages post type permalink, I'd like to add a '.php' to its end for example: `home_url() . post_name . '.php'`
I can't use WordPress permalinks page because I'm using it already like this: `/%category%/%postname%.php` and this doesn't affect the default pages post type.
**So I did it like follows:**
function wp_pages_permalink( $permalink, $post ) {
if ( empty( $post ) ) return $permalink;
return home_url( $post->post_name . '.php' );
}
add_filter( 'page_link', 'wp_pages_permalink', 10, 2 );
However I get a 404 when I try to visit the page, **and I have already flushed the rewrite rules by visiting the permalinks page**. | As suspected, this needed a rewrite rule.. I don't know why post_link filter didn't need a rewrite rule added..
function ba_rewrite() {
add_rewrite_rule('^([^/]*)?.php', 'index.php?pagename=$matches[1]', 'top');
}
add_action( 'init', 'ba_rewrite' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, 404 error"
} |
if custom post type exist
I want to test if custom post type `mobile` exist. I used if custom post type exist in the loop, but it doesn't work. Any suggestion why my code is not working
<?php /* The loop */ ?>
<?php if ( have_posts() ) : ?>...
<?php while ( have_posts() ) : the_post(); ?>
<? if( post_type_exists( 'mobiles' ) ) { echo 'The Products post type exists';} ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?pp echo 'The post type is: '. get_post_type( get_the_ID() ); ?>
<?php endwhile; ?>
<?php twentythirteen_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?> | You typed "mobiles" when you said you wanted to check for post type "mobile". So simply remove the s ;).
<? if( post_type_exists( 'mobiles' ) ) { echo 'The Products post type exists';} ?>
Should be:
<? if( post_type_exists( 'mobile' ) ) { echo 'The Mobile post type exists';} ?>
If it's still not working, triple check if you succesfully registered a post type named "mobile". | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "posts, customization, function exists"
} |
How to get more than 25 items via Simplepie RSS Feeds?
I have a feed with 50 items but seemingly no matter what I do, it always returns just 25.
`$feed->set_item_limit(50);` or `$rss_items = $rss->get_items(0,50);` none of these have any effect nor do I see any reference to the number 25 in the class source, I don't get it.
The feed is | include_once(ABSPATH.WPINC.'/feed.php');
$rss = fetch_feed('
$maxitems = $rss->get_item_quantity(50);
$rss_items = $rss->get_items(0, $maxitems);
print_r($rss_items);
Try this code.. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "rss, feed, simplepie"
} |
How do I add an article to specific page?
Regardless of it being WooCommerce or WordPress, I want to add a couple articles to specific pages, so they show there instead of the images that are there now. Homepage I know, I'm supposed to use shortcodes for that, but for some reason I can't get it to work. For example: This one has post ID 1305, so you'd imagine I use
[display-posts id="1305"]
to show it on that page, but it only displays the shortcode itself. I thought displaying posts by shortcode was one of WP's basic functions, wasn't it? Do I have to code a custom shortcode just for this to work?
Any advice? | If you want to put PHP code in the editor you need a plugin, same goes for display-posts.
Display Posts shortcode isn't a built in function. < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, pages, shortcode"
} |
PHP Warning missing Argument 1 for __()
I am getting this error in my server error logs:
[Thu Dec 11 10:06:30 2014] [error] [client 11.111.111.111] PHP Warning: Missing argument 1 for __(), called in /var/www/vhosts/mysite.org/public_html/wp-content/themes/mysite_v2.2/functions-cpt-projects.php on line 15 and defined in /var/www/vhosts/mysite.org/public_html/wp-includes/l10n.php on line 146, referer:
I've never encountered this before and I'm wondering what might be causing it. The line of code it refers to in the `l10n.php` file is:
function __( $text, $domain = 'default' ) {
return translate( $text, $domain );
}
I'm wondering if anyone knows how I might go about debugging this? I read somewhere that it could be related to a plugin and to disable them one by one to find out if the issue is resolved but this has not worked for me as of yet. | you get this error if you passed empty string or did not pass any argument to the `__()` function.
You should check where you've used the `__()` function and check what value is being passed as argument. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "php, l10n"
} |
upload_async.php returns 500 error
When uploading a large file via the Media uploader, I get the infamous HTTP Error problem. I also have the following in the Chrome console:
POST 500 (Internal Server Error)
The file is actually uploaded and appears in the uploads directory. I have tried all suggestions in the question linked above.
Wordpress version is 4.0.1 on 1&1 UK shared hosting
**Update**
With all plugins disabled, the error does not happen. If I enable, for example, revolution slider, the error occurs. However, I believe more than one plugin or a combination of plugins might be causing the problem. The fact that I am able to upload large images with all plugins disabled leads me to believe that a function or functions within certain plugins is interfering with async upload and that this is not a server config issue.
Other plugins causing the issue - uploadcare, fusion-core | It's a bit of a shot in the dark, but would you like to move up your memory limit? My guess is that your uploader fails on uploading big files with more serious plugins on just because they are using some of the memory too. In some cases "Memory exhausted" message does not appear if you don't have the right server settings.
In any case you should have a verbose error message somewhere in the web server logs, as 500 means exactly this: "There is an error on the server side and I'm not showing it to you, visitor!". | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "uploads, media"
} |
Check if the user has explicitly set an excerpt
Is there a way for me to check if the user has explicitly set an excerpt? I need to call the excerpt only if they've specified something in the excerpt field, and not an automatically shortened version of the content. | Try this:
if ( has_excerpt( $some_post_id ) ) {
// Do something here?
} else {
// Or here?
}
**References:**
* `has_excerpt` | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "functions, excerpt"
} |
Shortcodes in custom post fields without the_content()
I have created a custom post type which doesn't use `the_content()` to display anything in the front-end, just using echo's.
The user enters data into a text-area field in the plugin admin back-end, the CPT does some data manipulation and everything is output through a template file using a shortcode.
How can I get short-codes to fire when a user enters them into a CPT text-area in the backend admin. I can't see any filters being used. Also since it's an admin area text input field, php snippets won't work.
**EDIT:**
Perhaps a better question is how to implement `the_loop` properly in a custom post? My code currently;
<?php
/*
Template Name: Article
*/
?>
<article class="article-single">
<?php
echo do_shortcode('[banner]');
... loads of shortcodes to build up html...
echo do_shortcode('[info]');
?>
</article> | I ended up writing a basic function which used `preg_match_all` and `preg_replace` to find my short-code tags and sanitize the content before building the HTML output for the template page.
In my case, only useful if you have the one short tag being used.
function img_strip($str)
{
$preg = '/\\bimg\b\\[\/\bimg\b\]/';
preg_match_all($preg, $str, $matches);
if ($matches) {
foreach ($matches[1] as $match) {
$parsed = parse_url($match);
if (empty( $parsed['scheme'])) {
$match = '//' . ltrim($match, '/');
}
$replace = '<img src="' . $match . '" alt="floating-image" class="image">';
$str = preg_replace($preg, $replace, $str, 1);
}
}
return $str;
}
In future I will look into implementing the loop in my template with `the_content()`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, shortcode"
} |
If there is a comment_author_link put url around the avatar image
In the functions.php file for my theme the .commentslist shows a gravatar and if the user fills in a url in the comment form, you get a
comment_author_link()
Which prints a link with the name.
I want to put a link around the .avatar image IF there is a link. There is zip/zilch in the resources ([
It would be like this but this doesn't work:
<?php if ( has_comment_author_link() ) : ?>
<a href="<?php echo comment_author_url();?>" target="_blank">
<?php endif; ?>
<?php echo get_avatar( $comment, $size='75' ); ?>
<?php if ( has_comment_author_link() ) : ?>
</a>
<?php endif; ?>
But there is no such "`has_comment_author_link`" and I don't know how to create this.
Thanks! | Try this:
if( get_comment_author() == get_comment_author_link() )
echo get_avatar( $comment, $size='75' );
else
echo '<a href="' . get_comment_author_url . '">' . get_avatar( $comment, $size='75' ) . '</a>'; | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "comments"
} |
How to add add more properties to WP_Post object in search results loop
I am using a plugin called Event Organiser, and it seems that it will only append its custom properties to the post object for all other instances of the WordPress loop except the search. Is there a way to access the search loop only and inject these properties into each WP_Post instance in the results? | The custom properties you refer to are dates which a stored in a custom table, and which are joined onto the query for events. At this point in time, when querying events, this table is only joined when only the 'event' post type is being queried.
That is, you can search for events - but the dates are only pulled in if you are searching _only_ for events. The following snippet will ensure all front-end ("main") searches are for events only - which may or not may not be the desired behaviour, but you can of course target specific queries or simply set the post type to 'event' when you create your `WP_Query` object.
add_action( 'pre_get_posts', 'wpse172161_set_search_post_type' );
function wpse172161_set_search_post_type( $query ){
if( !is_admin() && $query->is_main_query() ){
$query->set( 'post_type', 'event' );
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, loop, search"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.