INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Css loads very slow
I have already searched about the problem but I didn't find something i understand, specifically for WordPress. Should I edit function.php of my theme somehow?
When the site loads the ugly sitemap appears and after a moment the site appears correctly.
I already fixed (only) the CSS errors seen in console and minified a big basic .css file
If you need the URL please tell me. | I assume, because you said that at first moment site is ugly and soon after that site looks fine that problem is in position of css in your HTML code. For example if you load external .css file in your footer it will load after everything above, so you will see your site "as ugly" because that part of your code is loaded before, and your browser do not now how to style your site, until it load css.
If that is the case, put your css in header of html. Also, if you provide site link I can see more. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, functions, css"
} |
I am using CloudFront and Cloudflare at the same time. Is that good?
I'm running my site using two CDNs. I primarily just use Cloudflare for security, and CloudFront for complete CDN. | You will likely get better performance out of using Cloudflare alone for both security and performance.
Cloudflare has the following performance advantages of Cloudfront:
* CDN WebP support in Polish
* Support for HPACK in their HTTP/2 implementation
* Ability to cache anonymous page views with WordPress
* Railgun
Additionally, Cloudflare has Flat rate pricing so no need to worry about bandwidth fluctuation, unlike with Amazon. In terms of network size, AWS in 16 cities where Cloudflare is in 101. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "cdn, cloudflare"
} |
Use htaccess to redirect wordpress non-existent page to homepage
For seo reasons I need to redirect domain.com/index.html and domain.com/index.htm pages to homepage without breaking anything. I tried some options so far but none of them work. Plain Redirect 301 commands get the site into redirecting loop. Here is what I've got so far
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [R=301] # this two lines
RewriteRule ^index\.htm$ - [R=301] # added by me
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule> | You can achieve that using
RewriteEngine on
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\.htm\ HTTP/
RewriteRule ^(.*)index\.htm$ /$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\.html\ HTTP/
RewriteRule ^(.*)index\.html$ /$1index.php [R=301,L] | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "htaccess"
} |
How to Remove Slug From Database?
**For example:**
* `mydomain.com/embed` automatically redirecting to homepage although I haven't set redirection.
* I want to add a page in my website name embed and for this page URL
automatically becoming `mydomain.com/embed-2`.
I checked everything, there is no existing or trash post, page, tags Etc.
**How to remove that existing embed slug from the database?**
Thanks | I don't exactly know about the word `embed`, but by default WordPress reserves & uses these sort of words for internal use. I tried to create a page slug named `embed` but it wouldn't work for me either on my localhost or on my live server. Maybe this is reserved for WordPress oEmbed functionality. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "permalinks, pages, database, urls, slug"
} |
How do I future proof my older WordPress theme?
The latest version of my WordPress theme has a bug. The version before it does not have this bug. Is it okay for me to stay on the previous version long-term? I don’t use many plugins, mainly HTML and custom CSS which are written for my child theme. Is it possible for me to make a particular version of my WordPress theme future proof? Specifically, compatible with future WordPress versions? | I'd say it's a security risk that will only increase with time. How do you see making it "future proof"? It's like asking a car manufacturer for a car that's accident-proof - they don't make these. That's what car insurance is for. The WordPress version you're on is only good for having protections against already-discovered vulnerabilities. New ones keep appearing, so patching them is part of the reason why new versions keep coming out.
So, to extend the analogy of automobiles, your "car insurance" would be to pick a reliable host with good support, keep your WordPress up-to-date, and follow best-practice advice for protecting WordPress site against attacks (lots of it out there, just do a simple web search) while balancing it against your particular situation (because not all security advice can always realistically be followed in all cases). | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugins, theme development, customization"
} |
How to add padding between posts
Ultimately, I'm really confused on how exactly you create a single class that affects each post in a static home page "recent post" type content area. I want to essentially have it where there's a post with a background, a space, then the next post with the same background, but not have the background behind all the posts. I hope that makes sense. Here's the code I have, but no matter what I do, I'm only able to add a class for one post at a time with the ID.
<ul>
<?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
<div class="new_home_single"><?php the_post()?></div>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php the_excerpt(__('(more…)')); ?>
<?php
endwhile;
wp_reset_postdata();
?>
</ul> | Wordpress already generates class for each posts, you can use these classes using the **`post_class`** function.
**Note:** The function can be used either within the loop or by passing the `$post_id`
So you would have
<ul>
<?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class( 'post' ); ?>>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php the_excerpt(__('(more…)')); ?>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</ul> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, wp query, post class"
} |
do I need to change the default database prefix?
when do one need to change the default database prefix OTHER THAN SECURITY REASONS?
Let's not worry about securities,so is there any preformance concerns?
See I have four or more worpdress site on one server(not multiplesites),like:<
All of them are using wordpress and sharing a same database prefix.Is there any problems for that when it comes to site preformance? | If it is easy to do, best practice is to have all wordpress installs use their own DB. Yes it is mainly for security, but it also simplifies tasks like importing and exporting sites.
If you must have several sites on one DB, then all of them have to have different prefix, and there is no other option, no matter if it is goor or bad for performance. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database"
} |
WordPress update 4.7 - the 70.000+ news posts became "Uncategorized"
Dear WordPress experts,
I updated a news website to Wordpress 4.7 from 4.6.1 or 4.6. The update ran well, the routine message showed up saying that the database as well should be updated. I clicked "OK". In a short while a 504 Gateway Timeout error occured. Afterwards, in the WordPress dashboard none of the 70.000+ posts has a category, all of the posts are marked as "Uncategorized". Once I try to edit and choose one of the 300+ categories and publish - nothing changes, the post remains "Uncategorized".
In PHPMyAdmin all the tables are fine, wp_terms is fine, all the categories with their IDs are listed there. However, the front-end and the WP-dashboard show no category to be assigned to a post.
PLease advise. | I have solved the issue. The max_execution_time (the time limit for server requests) was too short and seized the database update after 4.7 was installed.
I have just downgraded the WordPress version back to the previous version 6.1: \- WP-includes and WP-admin folders were overwritten along with the root files of the WordPress install (robots.txt and wp-config.php are not affected at all as they are not included in the fresh WordPress release files).
After the downgrade all the categories are fine, just the news articles that were published in the meantime had "Uncategorized" category that I easily removed and assigned them correctly in the dashboard.
The solution is easy - thanks for the help! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
What is the best way to disable my WP website if the user has adblocker on?
What is the best way to disable my WP website if the user has adblocker on?
But at the same time let the user know why and what they need to do. | Most plugins only give you the option to replace the ads with some other text but this plugin does the trick. If configured the right way you can work it so that a whole screen popup appears with no option to disable it(no close button) other than turning off the browser's adblocker and reloading the page. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "conditional content"
} |
When importing database, it shows error
I was importing my website' database on to another server but it is showing this error which I have no idea about:
 {
// Add theme support for Custom Logo.
add_theme_support( 'custom-logo', array(
'width' => 80,
'height' => 40,
'flex-width' => true,
) );
}
add_action( 'after_setup_theme', 'mymy_setup' );
In template:
<?php the_custom_logo(); ?>
The HTML output:
<a href=" class="custom-logo-link" rel="home" itemprop="url"><img width="80" height="40" src=" class="custom-logo" alt="" itemprop="logo" /></a>
What I need is:
<a href=" src=" /></a>
How to print without any ID & class? (I also can accept print logo URL only) | You can achieve this using the **`get_custom_logo`** filter.
add_filter( 'get_custom_logo', 'wpse250683_custom_logo_output' );
function wpse250683_custom_logo_output() {
$custom_logo_id = get_theme_mod( 'custom_logo' );
$attachment = wp_get_attachment_image_src( $custom_logo_id, 'full', false );
$attachment_url = '';
if ( is_array( $attachment ) )
$attachment_url = $attachment[0];
$html = sprintf( '<a href="%1$s"><img src="%2$s" /></a>',
esc_url( home_url( '/' ) ),
$attachment_url
);
return $html;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, templates, logo"
} |
WordPress text field in array problem
This my code.
$idsposts = solstice_get_opt('slider_4'); // example: 443,755,155,282
$myposts = array($idsposts); // must be array(443,755,155,282) but i saw array(443)
$blog_featured_post_args = array(
'post__in' => $myposts,
'orderby' => 'ID',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
);
What is my problem? This code get only 1 post (in example showing only 443 id post)
(sorry for my english) | It looks like you may be creating an array around a single long string that needs to be split up into array elements (assuming $idsposts is a string and not an array). Try using
$myposts = explode(",", $idsposts);
Instead of just adding $idsposts as the only element of your $myposts array.
You can also check if something is an array already using is_array($idsposts). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, wp query, array"
} |
Sidebar widgets are looping out of the sidebar wrapper
If there is no post and sometimes, the sidebar widgets are looping out of the sidebar wrapper.
sidebar.php
<div class="sidebar-wrapper">
<aside class="sidebar">
<?php if(!function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar')) : endif; ?>
</aside>
</div>
output:  {
$count_posts = wp_count_posts( 'product' );
return $count_posts->publish;
}
add_shortcode( 'product_count', 'product_count_shortcode' );
How can exclude one category? | I don't know of a direct method to achieve this, you should be able to get the category count using **`get_term`** then subtract that from the total.
function product_count_shortcode( $atts ) {
$data = shortcode_atts( array(
'cat_id' => 144,
'taxonomy' => 'category'
), $atts );
$category = get_term( $data['cat_id'], $data['taxonomy'] );
$count = $category->count;
$count_posts = wp_count_posts( 'product' );
return (int)$count_posts->publish - (int)$count;
}
add_shortcode( 'product_count', 'product_count_shortcode' );
From **iguanarama** answer:
You can also use **WP_Query**
$myQuery = new WP_Query ([
'post_type' => 'product',
'cat' => '-144',
'post_status' => 'publish'
]);
$count = ($myQuery ? $myQuery->found_posts : 0); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, shortcode"
} |
how to place ELSE on if function on multipostthumbnails?
Hello guys I am making a featured images but i want IF to have Else, maybe this is an easy question but i am is suffer. I don't know how to change this function to have ELSE
if (class_exists('MultiPostThumbnails')) :
MultiPostThumbnails::the_post_thumbnail(get_post_type());
endif;
i need here to have
else{
someimage
} | **Either**
if ( class_exists('MultiPostThumbnails') ) :
MultiPostThumbnails::the_post_thumbnail(get_post_type());
else:
//someimage
endif;
**OR**
if ( class_exists('MultiPostThumbnails') ) {
MultiPostThumbnails::the_post_thumbnail(get_post_type());
} else {
//someimage
}
**In regards to your comment:**
if ( class_exists('MultiPostThumbnails') ) :
$image = MultiPostThumbnails::get_the_post_thumbnail( get_post_type(), 'secondary-image', NULL, 'proimg', array('class' => 'img-responsive imgwid') );
if ( !empty( $image ) ) {
echo $image;
} else {
echo '<p>asdasdasdasdasdas</p>';
}
endif; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "thumbnails"
} |
Redirect one domain to another
How can I make all requests to pages at ` go to the same page but on `
htaccess currently looks like this...
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule> | Assuming you are using apache and have access to edit code files, add the following into your .htaccess file in the root directory of your site, somewhere right after the "RewriteEngine On" line.
RewriteCond %{HTTP_HOST} ^a.com [NC]
RewriteRule ^(.*)$ [L,R=301,NC] | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect"
} |
Activate a new WordPress Theme Only for Admins
I am going to change the theme of one of my site. I need to do lots of changes also for new theme.
So what I want to do is, I need to activate the new theme only for admins. When any other user visiting the site, it should use the current theme.
I tried following code but it did not work. It break the site.
Source : Show different theme for admin?
/*
Plugin Name: Theme Switch if Admin
Description: Display different theme to user if logged in as admin
Author: Kyle Barber
*/
add_filter('template', 'change_theme');
add_filter('option_template', 'change_theme');
add_filter('option_stylesheet', 'change_theme');
function change_theme($theme) {
if ( current_user_can('manage_options') ) {
$theme = 'twentyeleven';
}
return $theme;
} | At first, you should active the WordPress Debug mode to get the error after implement your code. The code should work, also tested on my environment. I use it on a client installation and works really well. See my source below. It is important that you use the right string for the theme slug, like here `popper`. You should also use this code as a plugin in the installation, not inside a theme. Also, the hint, if your installation is a Multisite \- the theme must be usable for each site, their use the small plugin to switch the theme.
add_filter( 'template', 'fb_change_theme' );
add_filter( 'option_template', 'fb_change_theme' );
add_filter( 'option_stylesheet', 'fb_change_theme' );
add_filter( 'pre_option_stylesheet', 'fb_change_theme' );
function fb_change_theme($theme) {
if ( current_user_can( 'manage_options' ) ) {
$theme = 'popper';
}
return $theme;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "themes, admin"
} |
modify text at the bottom of excerpt editor
I use an excerpt in a custom posttype and I would like to add or modify the existing text at the bottom of excerpt editor. I have no ideas ! Can someone help me ? Thanks | Try below code.
add_filter( 'gettext', 'excerpt_gettext', 10, 2 );
function excerpt_gettext( $translation, $original ) {
$post_type = get_post_type( $_GET['post'] );
if($post_type == 'your custom post type') {
$text = strpos($original, 'Excerpts are optional hand-crafted summaries of your content that can be used in your theme');
if ($text !== false) {
return 'My Custom Excerpt Discription';
}
}
return $translation;
}
**NOTE: Change "your custom post type" with your actual post type name**
Hope this will helps you | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "excerpt"
} |
CSS in child theme to replace !important in parent theme
I am trying to edit the colours of certain elements in my child theme on wordpress (the specific theme is Kleo if relevant). I have been doing fine adding in custom css to the child, however it seems the parent theme has labelled a few options as '!important' (at least that is what shows up when I inspect the elements in chrome). I'm not sure why they've done this but it makes for somewhat clunky code when I subsequently have to include '!important' on everything else I edit to overcome the parent's '!important'.
I was wondering if anyone knows of ways to edit the parent theme's css or of any other way of getting around this problem.
Many thanks for any help | You can overwrite an !important option with another !important but with a deeper selector. Example: the next snippet
.container {
width: 800px !important;
}
should be overwritten by
html .container {
width: 800px !important;
}
Thanks! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, child theme, parent theme"
} |
Permalink base only for posts
I am looking for special permalink mod, is this possible:
For posts to be like this: www.example.com/blog/nameofthepost
For pages to be like this: www.example.com/nameofthepage
Is this possible? Thank you | To get your desired structure:
Go to **Settings > Permalinks** in Admin.
Under **Common Settings** , click **Custom Structure** and enter `/blog/%postname%/`
Click **Save Changes** button.
This sets the permalink structure for posts. Pages already appear at at the root of your install, so no modification is needed for that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, customization, permalinks, pages"
} |
cookie free subdomain and @font-face
I've set up a cookie-free subdomain. In my css i use @font-face:
@font-face {
font-family: Butterfly Kids;
src:url(fonts/butterfly/Butterfly-Kids.ttf.woff) format('woff'),
url(fonts/butterfly/Butterfly-Kids.ttf.svg#Butterfly-Kids) format('svg'),
url(fonts/butterfly/Butterfly-Kids.ttf.eot),
url(fonts/butterfly/Butterfly-Kids.ttf.eot?#iefix) format('embedded-opentype');
font-weight: normal;
font-style: normal;
}
But the font does not appear. I've tried to set the path like:
src( format('woff'), etc.
This did't bring up the font either. Does anyone know how to set the path for @font-face with a cookie-free subdomain? Thanks for your interest. theo | @font-face does not require cookies (unless you choose to cache fonts to avoid server hits), and having a subdomain will make no difference either.
You may therefore have an issue with your URLs. Your paths in the first (multiple-line) example are relative to your css file; is your 'fonts' directory in the same directory as the css file? If not, that is your issue (or one issue).
Also, check your font file formats. All your fonts have 'ttf' (TrueType) as the first file extension, but they can't also be .eot (Embedded Open Type), .svg (Scalable Vector Graphics) and so forth: those are different file formats. Make sure all your font files are actually in the correct format. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, cookies"
} |
I want to create an archive and single page for a custom taxonomy for a custom post type
I have researched the heck out of this so forgive if I missed the answer somewhere...
I have registered a custom post type 'audiotalk'. Each talk can have one or more teachers so I registered a custom taxonomy for audiotalk called 'teacher' (non-heirachical).
I have an archive and single template for each audiotalk. I would like to find out if I can create an archive and single template for each teacher, with photo (I am using a plugin that associates an image with a taxonomy), description ($term->description) and that's pretty much it. The archive would simply be a list of teachers with links to their single page.
I've tried creating a single-teacher.php template but it's not working, meaning I am linking to, for example < and it's not using that template. In fact that page doesn't exist and I'm not sure why.
Can anybody enlighten me about what to do next? | You can achieve it using archive page in this case taxonomy-teacher.php
That page will return all the terms so you need to use "`get_queried_object()`" which will only show the data of that particular post.
Hope this answers the question. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, templates, taxonomy"
} |
help me remove this additional parameter in url
One of my websites is having an additional parameter `/?v=e5477cbee260` after the url. I do not understand what is this and how to remove it.I am using a godaddy hosted website . | The issue is caused by woocommerce.
Woocommerce has a setting called **Geolocate (with page caching support)** which adds this parameter to every your url.
The said option can be found in your dashboard at:
**Woocommerce → Settings → General → Default Customer Location**
Selecting any option apart from **Geolocate (with page caching support)** should resolve the issue | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "urls, parameter"
} |
exclude pingbacks from wordpress SQL query
Does anybody know how to exclude pingbacks from this query? I tried to add `AND post_type = 'comment'` after `AND post_password = ''` but this didn't work.
$query = "select
wp_posts.*,
coalesce((
select
max(comment_date)
from
$wpdb->comments wpc
where
wpc.comment_post_id = wp_posts.id
AND comment_approved = 1
AND post_password = ''
),
wp_posts.post_date ) as mcomment_date
from
$wpdb->posts wp_posts
where
post_type = 'post'
and post_status = 'publish'
and comment_count > '0'
order by
mcomment_date desc limit $limit";
Happy New Year! Even if you might not know the answer ;-) | You can achieve this by excluding `pingback` from the `comment_type` column of wordpress **comments table**
$query = "select
wp_posts.*,
coalesce((
select
max(comment_date)
from
$wpdb->comments wpc
where
wpc.comment_post_id = wp_posts.id
AND comment_approved = 1
AND post_password = ''
AND comment_type NOT IN ( 'pingback' )
),
wp_posts.post_date ) as mcomment_date
from
$wpdb->posts wp_posts
where
post_type = 'post'
and post_status = 'publish'
and comment_count > '0'
order by
mcomment_date desc limit $limit"; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query, sql, pingbacks"
} |
Is there a before_save_post hook or something similar
I need to check the value of a post status before is changed during a post update or even bulk update. And then depending on that value, adjust other values of the post
**Example:**
Lets say I have a custom post status
* status-one
* status-two
* status-three
I have post "A" who's status is **status-one**. So when I update this post to another status, **status-two** , I need to check if my old status was **status-one** or not?
I know this sounds a bit confusing. Please do let me know if there is any way I can clarify it. | There is a hook called `transition_post_status` which runs at every transition. You have both the old and new status available inside the hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks, post status, wp update post"
} |
How to combine 2 php functions into one function with a custom field
I'm trying to get 2 php functions with my custom field to work together with a custom field. they both work by themselves great but I can't get them to work together.
The first function hides the last X characters of a custom field
<?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo substr( $custom_field, 0, -6 ); ?>
The second function removes the spaces of a custom field
<?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo str_replace(' ', '', $custom_field); ?>
My optimistically simple attempt at a solution was/is a disaster...
<?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo str_replace(' ', '', $custom_field); echo substr( $custom_field, 0, -6 ); ?> | I had the same problem.
echo substr( $custom_field, 0, -6 );
echo str_replace(' ', '', $custom_field);
I think I solved it this way.
echo substr( str_replace(' ', '', $custom_field), 0, -6 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, custom field"
} |
wp_kses allow checkbox class and checked
I'm having a hard time getting `wp_kses` to allow the class for an input. These approaches didn't work:
input' => array(
'type' => true,
'class' => true,
'name' => true,
'value' => true,
'id' => true
),
also with `array()` for class it still is not returned.
Checked is also filtered.
Why do I need this? Well, long story short, the input is in a table which needs to be escaped prior to being printed with echo or with ajax. | According to the codex, you should define your **`wp_kses`** list of allowed html elements as below with `array()` instead of `true`
$allowed_html = array(
'input' => array(
'type' => array(),
'name' => array(),
'value' => array(),
'checked' => array()
),
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, ajax, escaping, wp kses"
} |
Which is the better way to write a conditional statement?
Which is better...
<?php if (is_page()): ?>
<?php else: ?>
<?php endif; ?>
or
<?php if (is_page()) { ?>
<?php } else { ?>
<?php } ?> | As far as I can tell, there's no performance difference. And both styles are acceptable by WordPress Coding Standards as you can read in:
> Braces should always be used, even when they are not required:
and
> Note that requiring the use of braces just means that single-statement inline control structures are prohibited. You are free to use the alternative syntax for control structures (e.g. if/endif, while/endwhile)—especially in your templates where PHP code is embedded within HTML
I always use the brace styles beucause I think is more widely known by PHP programmers of different levels and makes the block "hierarchy" much clearer and easier to understand.
Bottom line: you should choose what is more convenient to you. And whichever you choose, be consistent and stick to it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "conditional content"
} |
Get post terms for multiple posts at once?
I know I can get the terms for a single post using `wp_get_post_terms`, but is there a way (without writing a loop) to get all the terms in use by an array of posts? | That would be `wp_get_object_terms`. You'd need an array of post id's as the input, together with the taxonomy you want to retrieve the terms for (let's say: books). This should work (untested):
$my_query = new wp_query ($args);
$my_posts = $my_query->posts;
$my_post_ids = wp_list_pluck ($my_posts, 'ID');
$my_terms = wp_get_object_terms ($my_post_ids, 'books'); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "terms"
} |
adding tax_query to $query_string
I need to adjust the query in the loop.php by adding tax_queries based on $_REQUEST params. i tried something like this
$argsExtended = array(
'tax_query' => array(
array(
'taxonomy' => 'my_custom_tag',
'field' => 'slug',
'terms' => array( 'my_tag_slug' ),
'operator' => 'in',
),
)
);
$args = array_merge( $wp_query->query_vars, $argsExtended );
query_posts( $args );
but this doesn't seem to work. Any ideas? | the best way of doing this is **WP_Query**
$query = new WP_Query(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'my_custom_tag',
'slug' => 'slug',
'terms' => array( 'my_tag_slug' ),
'operator' => 'in',
),
)
);
and you should do the ajax callback like this
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action(){
//my custom code ...
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, query string"
} |
WP REST API: Order posts by meta value (acf)?
I'm requesting posts with the WP REST API and need to sort them according to an ACF field. It's value represents a date (numeric, jQuery date format yymmdd). I know how to do it with a normal WP_Query and tried to do the same using the rest api:
mydomain.com/wp-json/wp/v2/posts?filter[orderby]=meta_value_num&filter[meta_key]=my_field_name&filter[order]=DESC
In fact I'm using a custom post type that's registered with the rest api and everything else is working perfectly, so I think its not a cpt specific issue?
But the posts show up in default order (their creation date, latest to oldest). What am I missing? Is this orderby parameter not supported by the rest api? If so, how can I implement it myself?
Any other workarounds, suggestions? Really looking for a solution! Thankful for any hints! | I'm guessing you haven't exposed meta_key and meta_value to the REST API with the rest_query_vars filter, so this should do it:
function my_add_meta_vars ($current_vars) {
$current_vars = array_merge ($current_vars, array ('meta_key', 'meta_value'));
return $current_vars;
}
add_filter ('rest_query_vars', 'my_add_meta_vars');
Then you can refer to meta_key and meta_value in your query.
Be aware that this obviously exposes all your post metadata to the API, which has potential security implications; I believe that's why it's not activated by default. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "advanced custom fields, meta query, order, rest api"
} |
How to change the location of the menu
The theme I am using places the menu next to the logo (see the attached image). But I prefer to have the menu under the logo. How can I do it?  your Javascript file should be loaded, and (2) it relies on jQuery being loaded. You do this with wp_enqueue_script.
So put this in your functions.php file, replacing the path in quotes with the path to your (jQuery-dependent) Javascript file in your theme:
function my_jquery_script () {
wp_enqueue_script ('my-jquery-script', get_template_directory_uri () . '/js/my-jquery-script.js', ['jquery'], '1.0', true);
}
add_action ('wp_enqueue_scripts', 'my_jquery_script'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
} |
Is it possible to install two mail plugins together in a single Wordpress site? How to do it?
I am working for a site currently having MailPoet to send all the newsletters. We have around 800 subscribers and everything is configured properly and working fine.
Now, we got around 5000 emails for a new mailing list required only for a specific event that we are hosting. Mails need to be sent to these lists just once or twice. We do not want to upgrade Mail Poet for more subscribers. Instead, I found a new newsletter SendinBlue where I can send unlimited subscribers mails.
I do not wish to disturb the current newsletters through MailPoet but install SendinBlue side by side and send the new newsletters for one time use. Is it safe to activate SendinBlue along with Mail Poet and not hamper the mail plugin?
If not, how do I ensure to not mess up? Is there any other way to achieve the same? | You can install our WordPress plugin to synchronise your WordPress subscribers with your SendinBlue account and send newsletters. To do so, we invite you to refer to our step by step guide.
In addition, installing SendinBlue plugin for WordPress should not interfere with your current MailPoet plugin. We just ran a test with both SendinBlue plugin (Version 2.6.8) and MailPoet plugin (Version 2.7.5) activated and our plugin sent a newsletter smoothly.
Should you have more questions, please do not hesitate to send an email to contact(at)sendinblue(dot)com.
Regards, | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, subscription, newsletter, mailing list"
} |
How to make Link to go on the first post
I am wondering how to make a Link "Go to first post" While I have opened some post?
Any suggestion is welcome.
Thank you. | I'll assume by "first" you mean "newest", since if it's the oldest, then all you'd need would be the url of that post.
$latest = get_posts(array('numberposts' => 1));
$url = get_permalink($latest[0]->ID);
echo "<a href='" . $url . "'>Go to first post</a>";
This should give you a link that always goes to whatever is the latest post on your site. Where you add the code is dependant on your theme, as well as your personal preferences. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, links"
} |
How do I display post count of a custom post type with custom category taxonomy in wp_menu_nav?
I would like to display the post count of each custom taxonomy categories. Example:
Adventures menu:
Rafting (5)
Bunjee (1) | Here is your solution-
add_filter( 'wp_setup_nav_menu_item','the_dramatist_item_setup' );
function the_dramatist_item_setup($item) {
if ('taxonomy' === $item->type) {
$posts = get_posts( array(
'post_type' => 'post',
'numberposts' => -1,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $item->object_id, // Where term_id of Term 1 is "1".
'include_children' => false
)
)
) );
$item->title = $item->title . '(' . count( $posts ) . ')';
}
return $item;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy"
} |
Writing functions in WordPress functions.php that don't replace a WordPress core function
Using instructions from the WordPress codex, I have replaced/added to a number of WordPress core and theme functions. For these tasks, code, such as `add_action( 'after_setup_theme', 'mytheme_custom_header_setup');` are already putting the code to work in the right place of the processing.
Now, I have a situation where I want to move code from a custom WordPress template in a child theme into `functions.php` and call it from the template file as needed. In this case, essentially, I want to move code into `functions.php` that will include a few layers into a highly customized `front-page.php` after pulling in some custom field data.
Do child theme template files have access to `functions.php` or do I need to add some code somewhere to make that connection? | The child theme will have access to the functions in the parent theme's functions.php. Nothing you need to do. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions"
} |
Installing a theme on localhost, Ubuntu 16.04
I am using the LAMP stack, Ubuntu 16.04 LTS version.
I installed WordPress and am trying to install a theme which I have in a `.zip` file
When I try to install the uploaded theme (where WP clearly says I can upload a `.zip` file if I have it), I keep getting the following error
> "Are you sure you want to do this?
>
> Please try again."
If I try again, the same story repeats.
Is there any way to overcome this issue. I have to be able to install this particular theme on `//localhost`.
www-data has privileges to create and delete on all sub directories in `/var/www/html`. | The directory `/wp-content/` of your local installations needs permission to create directory. It is necessary to upload the package and unpack.
## rights
Maybe this should helps, if the user is `www-data`.
`chown -R :www-data /var/www/html/wordpress/wp-content/uploads`
`chown -R :www-data /var/www/html/wordpress/wp-content/upgrades`
Or full access to the wp-content directory `sudo chmod -R 777 wp-content/`
## php.ini
Also maybe the `php.ini` have not the right values to upload the package. Maybe you should try it with a small package. Or you change the php.ini of the LAMP, like the follow entries.
max_execution_time = 180
max_input_time = 600
post_max_size = 128M
upload_max_filesize = 256M
## helpful link
At least, a link to a helpful thread. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, installation, local installation"
} |
How to display the category featured images
I have a custom theme that for the latest posts displays the posts thumbnail. What I am looking to do is to check and if there is no thumbnail set then use the category's featured image. I could upload the images and use this:
if (!$photo) :
$uploads = wp_upload_dir();
$photo = '<div class="related-content-box__photo" style="background-image: url(' . $uploads['baseurl'] . '/2017/01/' . $category_name . '.jpg' . ')"></div>';
endif;
What I don't like about this is that if I want to change one image of a category I have to upload all of them again and change the year/month of the folder.
So I have uploaded the images as featured images for the category themselves but how can I display them? | The solution I found so far was to add featured image for categories as a custom field using ACF and then using the category ID to find and display each featured image.
Hope it helps anyone :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "categories, theme development, hooks, post thumbnails"
} |
Adding theme option values as custom body class
I'm looking to add some custom classes to the body element based on theme options.
I've setup two theme options ('rounded_corner_radio' & 'gradient_radio') that successfully output their values to the front-end using echo so I know they're working.
What I now need to do is insert those values into the body class but can't work out how. Here's what I currently have, any suggestions are very welcome.
<?php
$rounded_corner_radio = of_get_option( 'rounded_corner_radio' );
$gradient_radio = of_get_option( 'gradient_radio' );
function custom_body_classes( $classes ) {
$classes[] = $rounded_corner_radio;
$classes[] = $gradient_radio;
return $classes;
}
add_filter( 'body_class','custom_body_classes' );
?>
<body <?php body_class( ''); ?>>
Thanks in advance,
Tom | Review how the _variable scope_ works..
Let's not add yet another global variable, instead we can e.g. fetch the option values within the filter's callback:
function wpse251261_custom_body_classes( $classes ) {
// Get option values
$rounded_corner_radio = of_get_option( 'rounded_corner_radio' );
$gradient_radio = of_get_option( 'gradient_radio' );
// Assign new body classes
$classes[] = esc_attr( $rounded_corner_radio );
$classes[] = esc_attr( $gradient_radio );
return $classes;
}
add_filter( 'body_class','wpse251261_custom_body_classes' );
Note that we escaped it with `esc_attr()`, because the `body_class` filter is applied after such escaping in `get_body_class()`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, theme options, body class"
} |
Unable to link CSS file
I use this to link to my CSS file:
$css_file = plugin_dir_path( __FILE__ ) . 'MapStyle.css';
echo '<link rel="stylesheet" href="', $css_file, '" >';
Which (correctly) resolves as (echo $css_file):
/var/www/mysite/wp-content/plugins/TheMapPlugin/MapStyle.css
But the css file is never loaded, because the browser is looking for the file:
What am I overlooking here? All help appreciated! | First you need to register the style and css using wp_register_script() and wp_register_style() functions
//registering css
wp_register_style ( 'mysample', plugins_url ( 'css/MapStyle.css', __FILE__ ) );
wp_register_script ( 'mysample', plugins_url ( 'js/MapStyle.js', __FILE__ ) );
After this you can call the wp_enqueue_style() functions for loading the css in required page
wp_enqueue_style('mysample');
wp_enqueue_script('mysample'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, css, redirect"
} |
Accessing content from third party as native posts in Wordpress
Can Wordpress be architected to use external content accessed over HTTP instead of reading and writing to a database ? Size of the content available remote is simply huge and potentially modified by other tools as well. So importing into database is not a viable option.
Is there any product available that can abstract wpdb layer and use HTTP calls instead ? | Simple answer is "no". Whatever the API you might use it will be too slow to return a page in a timely manner, unless you have the other HTTP server on your LAN, in which case you should just access its DB directly.
What you can do is cache the "external" content in your DB and serve it the "normal" wordpress way. It means that instead of overriding the `wpdb`class you will need to write code in "higher layer" that will be responsible to sync items from the remote site whenever it is needed.
Other obvious options are to use iframes or oembed to embed the remote content in your wordpress pages. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, wpdb, http"
} |
Get image data from advanced custom field
I have created an image custom field using ACF which will be used as a featured image for each category. What I can't figure out is how to take that information and display it as a background image.
$category = get_the_category();
$category_id = $category[0]->term_id;
$category_image = get_field( 'featured_image', $category_id );
var_dump($category_image);
I have used the ACF documentation to write the above but this is displayed as "NULL".
Thanks in advanced! | To retrieve things out of a category, it's not quite as easy as passing just the category ID.
All taxonomies use the same layout: `'{taxname}_{term_id}'`
So, your example would be
$category_image = get_field( 'featured_image', 'category_' . $category_id ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "advanced custom fields"
} |
Concatenate Custom Field Value & HTML Value
I have the following code, and I am attempting to concatenate the values of the echo html code & 'the_meta'. Can anyone please suggest an edit to code to get this working?
**CURRENT CODE**
<?php echo '<p style="text-align:left;font-size:18px;margin-bottom:5px;">
<span style="color: #000000;">By AUTHOR FOR</span> <?php the_meta(); ?> </p>'; ?>
**DESIRED RESULT**
By AUTHOR FOR A GREAT MAGAZINE | To display `the_meta ()` after the 'by author for' text just needs a small change:
<p style="text-align:left;font-size:18px;margin-bottom:5px;"><span style="color: #000000;">By AUTHOR FOR</span> <?php the_meta (); ?></p>
However I'm not sure you want to use `the_meta ()`, because all values get displayed, and in an unordered list. (Reference: the_meta.)
Instead you probably want get_post_meta, so:
<p style="text-align:left;font-size:18px;margin-bottom:5px;"><span style="color: #000000;">By AUTHOR FOR</span> <?php echo get_post_meta (get_the_ID (), 'my-author-meta-key', true); ?></p>
Replacing `my-author-meta-key` with your meta key name, obviously. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, custom field"
} |
Backticks (`) Instead of Single Quotes (') in an SQL Statement?
I have this code which is partially shown here for brevity:
global $wpdb;
// creates jwp_bids in database if not exists
$table = $wpdb->prefix . "jwp_bids";
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`bid_amt` text NOT NULL,
When I originally typed the code, I used `'` within the parentheses and the code would not run.
I then changed the Single Quote to a Backtick and the code ran perfectly.
Would someone please explain:
* What is the proper term for the oddball quotes :)
* Why are they used instead of ' ?
* Is this only pertinent to MySQL? WP? Php?
* Where can I find a technical reference for this sort of thing so I don't have to bug you fine folk? | Backticks and regular quotes (both single and double) have distinct meanings in SQL. Quotes indicate a literal string, whereas backticks are quoted identifiers. This isn't specific to WordPress, but rather a general way in SQL of quoting columns or tables.
For example, imagine you're running a query comparing two columns:
SELECT * FROM wp_posts WHERE post_name = post_title
If you compare with single quotes (`'post_name' = 'post_title'`) this would compare the literal strings, which are never equal. However, with backticks, it would refer to the column.
Why use backticks at all? If a column is named the same as a reserved word in SQL, or contains a space, you need to quote it. For example, if you had a column called `count`, you'd need to quote that every time you refer to it, as `COUNT()` is a function (and hence, reserved word) in MySQL.
See also < | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "sql"
} |
Exclude posts with empty post_content in wp_query
is it possible to exclude posts with empty post content from a wp_query?
$args = array(
'post_type' => array('post'),
'posts_per_page' => 5,
'post_status' => 'publish',
);
$query = new WP_Query($args);
$posts = $query->posts;
foreach($posts as $post) {
var_dump($post->post_content);
}
Doing it inside the loop like `if($post->post_content !== '') { }` is not an option. Because my list won't have 5 items. | This isn't possible with a standard WP query, and you'll have to leverage the use of `posts_where` before the `WP_Query` is called.
function the_dramatist_filter_where($where = ''){
$where .= " AND trim(coalesce(post_content, '')) <>''";
return $where;
}
In the above, we're simply only selecting posts where the column `post_content` isn't empty.
Then add the filter.
add_filter('posts_where', 'the_dramatist_filter_where');
Now perform the query.
$query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 8));
And then when you're done, remove the filter from the query so it doesn't interfere.
remove_filter('posts_where', 'the_dramatist_filter_where'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "posts, wp query, query, query posts, post content"
} |
plugin generated unexpected output during activation, but it is empty
I am getting this error what is already answered in several threads here with same problem. Here the error message:
> The plugin generated 3 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
_Plugin that causes this error is written by me._ To find out I deleted the complete code and only left the documentation block at the top.
Still get the error when activating my plugin even when it is empty! There is no cache running.
Find this very weird. How can an empty plugin generated the same error as when it is filled with code?
Someone of you any idea how to solve this? Would be very nice. I do not understand this. | You may have empty characters at the beginning before the `<?php` block.
You may also try to `var_dump($result->get_error_data())` this error message -- this would be the dirty way.
File: wp-admin/plugins.php
42: $result = activate_plugin($plugin, self_admin_url('plugins.php?error=true&plugin=' . $plugin), is_network_admin() );
43: if ( is_wp_error( $result ) ) {
44: if ( 'unexpected_output' == $result->get_error_code() ) {
45: $redirect = self_admin_url('plugins.php?error=true&charsout=' . strlen($result->get_error_data()) . '&plugin=' . $plugin . "&plugin_status=$status&paged=$page&s=$s");
46: wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect));
47: exit;
48: } else {
49: wp_die($result);
50: }
51: } | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, wp error"
} |
Buddypress profile pictures sync across Wordpress Multisite Network
I am setting up a Multisite Network project. All websites will be handled with SUBDOMAIN_INSTALL. One of the websites will have BuddyPress, it will also serve as an entry point to the network. User will register through buddypress.domain.com and from there it will have access to other sites (portals, shops...)
I managed to setup user sync, so username and passwords are stored networkwide, but the problem is profile picture.
When user ads profile picture through BuddyPress it won't sync on other sites, so if they leave a comment on the portal site, their avatar is empty.
Is there a way to syncronize BP user avatar across the entire network of websites? | After activating multisite I installed and network activated BuddyPress. I also added this line to wp-config.php: define ( 'BP_ROOT_BLOG', 2 ); where 2 is ID of your communitycommunity.mysite.com
That way BP is accessible from an entire network, but profiles are handled only from the network site.
On network sub site users update their profile info, pictures etc and the changes are reflected across the network. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "buddypress, multisite user management"
} |
Pretty Filter URL
I'm developing an calender. It works very well for. My last point on the list is "make the url pretty".
Currently I have a **page** (example.com/my-calendar/) with a custom **php-template** which renders the calender sheet. It is displayed only one month per page. By a `$_GET` parameter I'm displaying the right sheet.
That means the URL `example.com/my-calendar/?base_date=05-2017` displayes me the calendar sheet for **may 2017**. But I wanted to have the URL like:
`example.com/my-calendar/05-2017`
or
`example.com/my-calendar/may-2017`
I'm playing around with this tutorial but did'nt get it work. | Here is my current code:
function hm_base_date_query_vars($vars) {
$vars[] = 'base_date';
return $vars;
}
add_filter('query_vars', 'hm_base_date_query_vars');
function hm_base_date_rewrite_rule() {
add_rewrite_rule(
'^my-calendar/([^/]*)/?',
'index.php?pagename=my-calendar&base_date=$matches[1]',
'top'
);
}
add_action('init', 'hm_base_date_rewrite_rule', 10, 0);
$base_date_test = get_query_var('base_date');
on the url `example.com/my-calendar/foo` my var `$base_date_test` returns `null`
Maybe someone can help me. Thanks.
**// Edit:** It works. I tried to call the var in functions.php but I had to call it in my custom php template -.- | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, url rewriting, rewrite rules, query variable"
} |
Add custom field to all posts in specific post_type
I want to add custom field 'tnid' to all my posts, and have it's meta value taken from field 'name'
i have the following working query:
INSERT INTO wp_postmeta (post_id, meta_key, meta_value)(
SELECT post_id, 'tnid', meta_value
FROM wp_postmeta
WHERE meta_key='name')
Now to my question. I want to add the new custom field only to post_type 'post', not to any other post_type. How do i have to edit the SQL query to accomplish that? thx | Hope this below SQL query will solve your problem-
INSERT INTO wp_postmeta
(post_id,
meta_key,
meta_value)
(SELECT post_id,
'tnid',
meta_value
FROM wp_postmeta
WHERE meta_key = 'name'
AND post_id IN (SELECT id
FROM wp_posts
WHERE post_type LIKE 'post'))
Please try it first. I haven't got the chance to try it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field, post meta, mysql"
} |
Set default options for inserting media
Is it possible to set default options for inserting image into article. I want every image to link to full image and be right aligned. Setting this manually every time is annoying and unproductive.
Can I do this with some hook in my functions file? | You can do this in two ways. If you want to keep it theme specific, edit your `functions.php` file with this code:
add_action( 'after_setup_theme', 'my_new_default_image_settings' );
function my_new_default_image_settings() {
update_option( 'image_default_align', 'right' );
update_option( 'image_default_link_type', 'file' );
}
The other way to do it is more general, but also more rigid:
1. Go to YOURSITE.COM/wp-admin/options.php
2. Find the `image_default_link_type` field.
3. Type in `file`.
4. Find the `image_default_align` field.
5. Type in `right`.
6. Scroll to tho bottom and hit Save.
Some helpful references:
* WP Codex: <
* Credit for the technique: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, hooks, options, customization"
} |
Levels of caching and impact on the WordPress web site
Recently I have tried to answer this question and I noted how important is to understand the caching when solving Wordpress problems.
Namely, I just wanted to summarize the possible levels of caching that may exist between the web browsers and WordPress website.
There is:
* A browser caching
* Possible proxy web server caching
* WordPress plugin caching (W3TC, ...)
* Webserver software caching (Like Redis, Memcached ,...)
* WordPress query caching
* MySQL caching
* PHP opcode caching
* Maybe more
This may look complex but if I add custom version to the URL like `?version=3.14` will all possible caches be defeated? | Adding custom variables(query strings) to **static resources** doesn't affect caching at some of the levels you've listed above:
* WordPress plugin caching
* Webserver software caching
* PHP opcode caching
* MySQL caching
* WordPress query caching
* Several more etc.
All of these don't cache static resources(js, css and so on) but rather cache the output of application codes at their different applied levels.
Most Proxy Servers, CDNs and browser cache prevent caching static resources with query strings as it is a common method used for breaking cached objects so caches at the **browser cache level** for instance would be invalidated when the query strings are updated.
To my knowledge, this might be because caches of static resources are actual copies of the static files stored with the headers and references to the object's url. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "cache"
} |
I want edit_post_link() to open in a new window/tab (target="_blank")
I'm trying to make posts as easy to edit as possible. When a person clicks on "Edit Post", the default is to open in the same window. This can be frustrating, because it's a little difficult to quickly get back to the page they clicked "Edit Post" from (the blogroll).
Obviously, they could right-click > "Open Link in New Tab" (or Command-click), but I was wondering if there's a way to add `target="_blank"` to the edit_post_link(). Is that possible? | You can adjust the link via the `edit_post_link` filter.
Here's an example where we use a simple replace since we don't have the `class` and `url` explicitly as input arguments:
add_filter( 'edit_post_link', function( $link, $post_id, $text )
{
// Add the target attribute
if( false === strpos( $link, 'target=' ) )
$link = str_replace( '<a ', '<a target="_blank" ', $link );
return $link;
}, 10, 3 ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "theme development"
} |
Style the last element having a specific class
I have a code like this.
<div class="slick"></div>
<div class="slick active"></div>
<div class="slick active"></div>
<div class="slick active"></div>
<div class="slick"></div>
<div class="slick"></div>
I want to style the last div having the class 'active'. Is there any way to do this? | There is no (good) way to solve this problem in its current state with CSS. The best solution is to add an extra class to the last active div, or to use javascript
See this question for more details | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "html, css, select"
} |
PHP notice coming from the WordPress core?
Do you also experience this particular notice? ( Of course one has to turn on the DEBUG mode at the wp-config.php to be able to see this kind of a notice ).
> Notice: add_shortcode_param is deprecated since version 4.4 (will be
> removed in 5.1)! Use vc_add_shortcode_param instead. in
> F:\inetpub\wwwroot\.......\wp-includes\functions.php on line 3783
Since this is coming from one of the core files, it has puzzled me as how it made it to production as such or I'm reading this entire thing in a wrong way. | 1) Looks like you are using the Visual Composer Plugin which is a legacy version which has a deprecated function. If you are using old version upgrade your Visual Composer plugin to the latest version which is **5.0.1**.
2) Another case might be your are using a theme which might be using Visual Composer as a third-party plugin and has some Visual Composer Addons which is not updated and still uses that `add_shortcode_param`
**Manual Solutions** Find in theme files for `add_shortcode_param`. If it doesn't show any then look for the same in your third-party plugins used by your theme and if found then replace those function names with `vc_add_shortcode_param` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "errors, core, notices"
} |
How to view menu and submenus in URL
I created a menu to my Wordpress website, and I have a menu like this
MENU1
..submenu2
...submenu3
if I click on submenu3/submenu2 then the URL is like,
abc.com/submenu3 or abc.com/submenu2
what I exactly want to do is like,
abc.com/menu1/submenu2/submenu3
Please reply me your answer, I really need it. Thanks in advance. | If you dont want to do any back end coding you can create a custom link in the menu panel
{
if(is_front_page()){
wp_enqueue_style('front',get_template_directory_uri().'/css/front.css');
}else{
//some code
}
}
add_action('init','adding_front_style');
My front-page.php
<?php get_header(); ?>
<div class = "search">
<?php get_search_form() ?>
</div>
My front.css
.search{
background-color: blue;
} | Wrong choice of hook, `Init` hook Fires after WordPress has finished loading, so what you have thought is right. But `wp_enqueue_scripts` hook is required to load JavaScript and CSS.
Replace line `add_action('init','adding_front_style');` with `add_action('wp_enqueue_scripts','adding_front_style');` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, theme development, css, frontpage"
} |
Wordpress activate theme error $pagenow
I will start from the beging, I am migreting wp website, ant everything went fine. When I try to activate theme I get this error, also tried installing again theme , still same, other theme works fine. All plugins disabled, child theme, new wp install,nothing.
Notice: Undefined variable: pagenow in /home/xxx/public_html/wp/wp-content/themes/themefolder/inc/activation/class-tgm.php on line 79
Notice: Undefined index: action in /home/xxx/public_html/wp/wp-content/themes/themefolder/inc/activation/class-tgm.php on line 79
This is the part of the code giving problems:
}
if (is_admin() && (($pagenow == 'themes.php') || ($_GET['action'] == 'activate') || (isset($_GET['plugin']))) ) {
if (isset($_GET['plugin']))
{
global $wpdb ;
}
$install_code = | `$pagenow` is a global, just like you do with `$wpdb` later on in your code you should call `global $pagenow;` before trying to use it
and `$_GET['action']` is only set when ?action= is in the url, this isnt always the case. Always make sure it is set before trying to use it:
`if( isset($_GET['action']) && $_GET['action'] == 'activate' )` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, wp admin, child theme, theme options"
} |
Unable to install theme recommended plugins on Multisite
I uploaded and activated the theme on my multisite network successfully. After this, I was trying to install the plugins that come bundled with the theme but when I clicked on install, it is showing this error.
` condition. So you don't have the access right.
if ( !can_edit_network( $details->site_id ) )
wp_die( __( 'Sorry, you are not allowed to access this page.' ), 403 );
Work on your access rights. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, multisite, themes, errors"
} |
Broken link to theme asset after restoring backup
Restoring site's backup, results in not loading sites asset e.g. style.css and .js files. I checked the site and notice the link to theme asset:
site.com%20/wp-content/themes/themename/style.css
as you can see, the `%20` after the domain is cause the problem. The link above generated from bottom code in functions.php:
wp_enqueue_style( 'theme-style', get_stylesheet_uri() );
I checked Site URL in wp settings and it's Ok, also links in functions.php are Ok. So where should I go from here ? Where that extra **%20** came from ?
Thanks. | Check your wordpress db table wp_options and from there check option name : siteUrl and home url and change %20 from there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes, backup"
} |
Function coding error concatenating quotes I think
Function:
function get_highest_bid(){
global $wpdb;
$postid = get_post_id();
$table = $wpdb->prefix . "jwp_bids";
$highest_bid = $wpdb->get_var(
"Select max(bid_amt)
FROM " . $table . "
WHERE post_id = " . $postid . ';" );'
echo $highest_bid;
}
Error: Unexpected echo line blah blah.
Question: What did I do wrong concatenating that `; );` at the end? Concatenating when quotes are part of the statement confuses the dickens out of me. Any tips on that?
Thanks! | If you're evaluating php variables in a string(interpolating the variables directly in a string), it's best to use double quotes, this way you don't have to concatenante with dots.
function get_highest_bid( ) {
global $wpdb;
$postid = get_post_id();
$table = $wpdb->prefix . "jwp_bids";
$highest_bid = $wpdb->get_var(
"Select max(bid_amt)
FROM $table
WHERE post_id ='$postid';"
);
echo $highest_bid;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions"
} |
Overriding a parent theme folder in the child theme
I have a parent theme that refers to an image in the theme's `img` folder like so;
<button id="buy" type="submit"><img src="<?php bloginfo('template_directory'); ?>/img/Buy-Now-Button.jpg" border="0" width="160" height="47" title="" alt="Buy One" style="cursor:pointer;"></button>
However, I thought that if I activated a child theme and then within that child theme there was another `img`folder with a different Buy-Now-Button.jpg then that would be used instead of the one in the parent them.
My aim is to allow users to use their own buy now button if they want to simply by placing it in the child theme img folder, am I going about this the right way? | Try using `get_stylesheet_directory_uri()` instead of `bloginfo('template_directory')`.
This function will give you the path to the `style.css` of your currently activated theme (the child theme). From there you can navigate to all sub-folders in your child theme folder.
<button id="buy" type="submit"><img src="<?php get_stylesheet_directory_uri(); ?>/img/Buy-Now-Button.jpg" border="0" width="160" height="47" title="" alt="Buy One" style="cursor:pointer;"></button> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "child theme"
} |
src script only works on home page?
Okay, so when I include my header in any page besides the home page, and I inspect the page, all of the calls show as errors because it's adding that page to the root of the source call. How do I change that?? Here are some of my calls:
<script src="wp-content/themes/gamer_meld/js/jquery.flexslider.js"></script>
<script src="wp-content/themes/gamer_meld/js/fancySelect.js"></script>
<script src="wp-content/themes/gamer_meld/js/script.js"></script> | First, don't put script tags directly in template files, enqueue them from your theme/child theme's `functions.php`. Second, use the API to output URIs for scripts, don't hardcode or use relative paths.
function wpdocs_theme_name_scripts() {
wp_enqueue_script(
'flexslider',
get_template_directory_uri() . '/js/jquery.flexslider.js',
array('jquery'),
null,
true
);
wp_enqueue_script(
'fancyselect',
get_template_directory_uri() . '/js/fancySelect.js',
array('jquery'),
null,
true
);
wp_enqueue_script(
'myscript',
get_template_directory_uri() . '/js/script.js',
array('jquery'),
null,
true
);
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
How do I get more image editing options in the admin?
In an installation of Wordpress 4.7, when I go to edit an Media | Library | Some Image | Edit Image I am offered editing options such as, "Restore Original Image" and "Thumbnail Settings".
 on GIFs in Wordpress 4.5.3. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images, post thumbnails"
} |
Installation problems on a domain-name-less server
Is it possible to install WordPress on a public server that doesn't have a domain name configured yet? I thought I'd set it up on IP-only, and had the line `server_name _;` in my Nginx configuration. I think it's because of this that the WordPress installation dies at `wp-admin/install.php?step=2` and I see the following error in the Nginx logs:
2017/01/08 07:24:53 [error] 25686#25686: *22 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught phpmailerException: Invalid address: wordpress@_ in /home/ankush/wp_main_site/wp-includes/class-phpmailer.php:946
Stack trace:
#0 /home/ankush/wp_main_site/wp-includes/pluggable.php(352): PHPMailer->setFrom('wordpress@_', 'WordPress', false)
#1 /home/ankush/wp_main_site/wp-admin/includes/upgrade.php(395): wp_mail('dkasolutions.sa...', 'New WordPress S...', 'Your new WordPr...')
Is a domain name a must or am I doing something wrong? | Set `server_name` to the IP address, eg:
server {
listen 80;
server_name 0.1.2.3;
// other stuff
}
You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate `$_SERVER['SERVER_NAME']` and similar values … will just break.
See ticket #25239 for the progress on this front.
If only WordPress had a `Request` object, like everyone else. Then it would be easy to prepare all these global values. See Symfony for an example. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 6,
"tags": "installation, domain"
} |
browser showing connection was reset while accessing posts from local host
I was coding a custom theme. Posts showing connection reset problem message where as pages are loading fine. I found adding js to my single.php causing this error.here is my code to add js file.
function adding_sidebar_js(){
if( is_single() {
wp_enqueue_scripts( 'singlejs', get_template_directory_uri(). '/js/sidebar.js' );
}
}
add_action( 'wp_enqueue_scripts', 'adding_sidebar_js' );
Can you explain why I am getting this error? | It was syntex error in my functions.php which causing the error. In the if statement it was not `wp_enqueue_scripts`. It was `wp_enqueue_script` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp enqueue script, single"
} |
Header with content
I want to make a large header with logo, navigation and centered title and some text below. I dont know how to make that centered title and text below so that end user can edit title and text in admin panel.
I have an idea to get some post data into header.
$post = get_post($post_id = 1);
echo '<h1>'.$post->post_title.'</h1>';
echo '<p>'.$post->post_content.'</p>';
Maybe create special page template for that purpose? How to tell wordpress that this page goes to header. | This thing is based on your template.If your template allow you to add your own code then you can add this code in your template part.
In your active theme you can see **header.php** file, in this file you can add this code where it is suitable. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "headers"
} |
Custom Fields through plugin in a Custom Post Type
I'm new to wordpress and would like to know what's the best way of extending my custom plugin for our school page. I've created a custom post type experiment which will always have steps 1 to N. Sometimes an experiment might have 3 steps and sometimes 12 steps.
I've looked at custom fields and from the documentation the key-value storage would require always having the maximum number of fields and then checking if a key's value is empty when iterating through it inside the template.
What I'd like to do is to have ajaxed fields like there are for a normal post. | So I figured out that Wordpress works with arrays inside a custom post_meta by default. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, plugins, custom field"
} |
Sorting columns with aliases
I am new to WP_LIST_TABLE and working on someone's else code. I have a couple of joins my query which you
SELECT *
FROM wp_o_students st
INNER JOIN wp_o_schools sc
ON st.school_id = sc.school_id
INNER JOIN wp_marks_list ml
ON st.student_id = ml.student_id
ORDER BY $orderby
LIMIT %d OFFSET %d
How do I set these columns to be sortable ?
'school_id' => __('School ID', 'olympiad'),
'student_id' => __('Student ID', 'olympiad'),
'test_code' => __('Test Code', 'olympiad'),
'division' => __('Division', 'olympiad'),
'class_highest' => __('Class Highest', 'olympiad'),
'cutoff_marks' => __('Cutoff Marks', 'olympiad'),
'scored_marks' => __('Scored Marks', 'olympiad'),
'marks' => __('Marks', 'olympiad'));
If I put aliases before column names, it won't work. It shows no results in table and its empty. What am I missing here? | Well, I found out that this can be achieved in 1 way. If I specify specific columns that I need instead of using * in my query, it will work.
Example:
SELECT st.student_id
FROM wp_o_students st
INNER JOIN wp_o_schools sc
ON st.school_id = sc.school_id
INNER JOIN wp_marks_list ml
ON st.student_id = ml.student_id
ORDER BY $orderby
LIMIT %d OFFSET %d
And for table columns:
'student_id' => __('Student ID', 'olympiad'),
Since there will be only 1 column with student_id, it will be used. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp list table"
} |
Include Javascript as Plain (No file inclusion)
Is there a way to append Javascript to the body in the script tag without using a file? Normally you would do it with
wp_enqueue_script('name', 'path/to/js/file');
Is there a way to include js in the script tag directly?
Like:
<script>My awesome code </script> | Yes, you can directly insert what you want in the header or the footer using the action `wp_head` or `wp_footer`
add_action('wp_head', 'custom_script');
function custom_script(){
?>
<script>My awesome code </script>
<?php
}
You only have to put this in functions.php of your child theme | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "javascript, wp enqueue script, include"
} |
Category pagination shows same posts
My blog is showing same posts on every page, but this is only happening with Category Pagination (maybe with Tag Pagination too). You can't see the problem in the front page.
Front page: <
Category page: <
The only pagination plugin I'm using is "Category pagination fix". I've already tried deactivating it, but nothing happened.
Searching around, I've tried several suggestions, however, I am not an expert when it comes to PHP so I could really use some help here.
Can you shed some light?
Thank you.
Giovanna | This generally happens when you don't use some fixed term in the URL for category. For example, instead of:
`
The category link can be:
`
The setting is in `WordPress Admin` => `Settings` => `Permalinks`.
Here, either you keep `Category base` blank or write a term like `category`, `topic` etc.
However, from your source code, it looks like you placed a dot `.` in there or used a setting from **Yoast SEO** to hide the term `category` from URL. Hiding the terms like `category`, `tag` etc. are possible, but often causes problem such as this if you are not careful. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "pagination"
} |
get_option('admin_email') not working in wordpress when using ajax call
So I've been working in Wordpress lately with Ajax and I managed to get some stock data into my site from my database. However, I am now trying to use Ajax to load Wordpress posts into my left sidebar, which requires the use of Wordpress functions and it seems as if I am not doing this properly.get_option() shows NULL on this.
JS
url:"<?php echo get_template_directory_uri(); ?>/sendContactForm.php",//request URL
type:"POST",//Request type GET/POST
data: $(_this).serialize()
PHP(sendContactForm.php)
$result = new stdClass();
$from = $_REQUEST['email'];
$message = $_REQUEST['message'];
$sender = $_REQUEST['email'];
$result->message = $message;
$result->subject = $_REQUEST['name'] . " send you a message";
$result->to = "get_option('admin_email');
$result->to = "get_option('admin_email'); showing NULL | I confess that I'm slightly confused by how your sending email function loads posts into your sidebar...the code does not seem to be doing the thing that you described.
Are you loading WordPress in sendContactForm.php? Is what you've shown here the only code in sendContactForm.php?
`get_option()` is a WordPress function, so you need to load WordPress to do this. This is usually done by putting something at the top of your php file like:
`require('../../../wp-load.php');`
But that's a bit hacky.
The proper way to do AJAX in WordPress is to send your POST request to `/wp-admin/admin-ajax.php` with an parameter like `action=sendContactForm` and then create an action hook like this:
add_action('wp_ajax_sendContactForm', 'my_email_function');
add_action('wp_ajax_nopriv_sendContactForm', 'my_email_function');
function my_email_function() {
// process request here
wp_die();
}
Read more about this at: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "php, javascript"
} |
Add space under featured image in singel post
anyone can help me? How to add space of featured image in single post.
;
Is it working if users just put '[email protected]' in the whitelist? Or what should they use? | Honestly, this also has nothing to do with WordPress. It is more web server whitelisting issue. You should start with this link.
SPF records are important.
And maybe your web server has IP address that is blacklisted. You may even consider different IP address from your provider. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "email, wp mail"
} |
How to Modify Existing Rewrite Rules?
I'm attempting to modify existing rewrite rules generated by WordPress in order to override the default rewrite rules generated.
I'm using the filter hook `rewrite_rules_array` to obtain an array of existing rewrite rules.
While sifting through the rewrite rules array, there are rewrite rules containing `$` in the array value.
After replacing a set of array key/value pairs, PHP is interpreting the suffix text of the array value containing `$` as a PHP variable.
**For example:** `&feed=$matches[1]`.
When I'm done with my modifications and dump the array, everywhere with `$matches[1]` just appears blank.
**My question is:** How can I get `&feed=$matches[1]` to output as `&feed=$matches[1]` in my array value instead of outputting like `&feed=`?
Both my array keys and array values of the modified rewrite rules are contained within double quotes. | Wow I feel like a huge newblet. This is incredibly simple. Just escape it with a `\`.
`"&feed=$matches[1]"` should be `"&feed=\$matches[1]"`.
EASY. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "permalinks, url rewriting, urls, rewrite rules, query variable"
} |
Change Structure Permalink => Error 404? How to redirect
i have a problem with Permalink as: former, i have set Structure Permalink as: `/abc-%postname%/` now i change (remove `abc-`) and set Structure Permalink to `Post name as /%postname%/` but all my link is error 404.
Any idea for auto redirect Permalink `/abc-%postname%/` to `/%postname%/`
Thank you very much. | You can use a rule in your `.htaccess` (a file that will be in the root folder of your WordPress installation) - add this to the very bottom:
RewriteEngine On
RewriteRule ^/?abc-(.+)/?$ /$1/ [R=301,L] | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "permalinks"
} |
Removing Facebook contact field from user contact not working
I'm trying to unset the Facebook link for users who registered in the past 365 days. For users who have completed more than a year, don't unset.
Here's my code which is not working:
function modify_user_contact_methods( $user_contact ) {
get_currentuserinfo();
$user_data = get_userdata($user_ID);
$registered_date = $user_data->user_registered;
if (strtotime($registered_date) > strtotime('-365 days')){
// Remove user contact methods
unset( $user_contact['facebook'] );
}
return $user_contact;
}
add_filter( 'user_contactmethods', 'modify_user_contact_methods' );
It shows the field. If I remove the condition, it unsets for every user. So the set/unset is correct, only the 365 condition is wrong, I guess. But it seems correct, what amI doing wrong? Please guide. | Firs things first... always, always enable debugging. Secondly, you should accept the `$user` parameter in your callback - otherwise you are always checking the _logged in user_ , not the user within the current context:
function modify_user_contact_methods( $methods, $user ) {
if ( ! $user instanceof WP_User ) {
if ( ! $user = wp_get_current_user() )
return $methods;
}
if ( strtotime( $user->user_registered ) > strtotime( '1 year ago' ) ) {
unset( $methods['facebook'] );
}
return $methods;
}
add_filter( 'user_contactmethods', 'modify_user_contact_methods', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "functions, customization, contact"
} |
Security issue with 'paged' and 'posts_per_page' parameters taken directly from a POST request?
I was wondering if this poses any security risk:
$current_page = $_POST['page'];
$posts_per_page = $_POST['posts_per_page'];
$result = new \WP_Query([
'posts_per_page' => $posts_per_page,
'paged' => ++$current_page,
'post_type' => 'post'
]);
Since I take `posts_per_page` and `paged` directly from a POST xhr request, someone could enter whatever values they want.
I see here that `posts_per_page` and `paged` are listed as `int`, but could someone use e.g. SQL injection in this case nonetheless? | Currently we have the following typecasting in the `WP_Query` class (see here):
$q['posts_per_page'] = (int) $q['posts_per_page'];
if ( $q['posts_per_page'] < -1 )
$q['posts_per_page'] = abs($q['posts_per_page']);
elseif ( $q['posts_per_page'] == 0 )
$q['posts_per_page'] = 1;
and here:
if ( isset($q['page']) ) {
$q['page'] = trim($q['page'], '/');
$q['page'] = absint($q['page']);
}
Instead of running the query for every user input, hoping the core will handle it somewhere, **validate** it beforehand and only run the query if it's of correct type and range. You could check for a positive integer here and have a max allowed value, e.g. 100, because you don't want to allow e.g. 9999999 that could seriously slow down the whole site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "security"
} |
Is it fair to use MIT licensed code in WordPress plugins?
Is it fair to use an MIT licensed jQuery library inside a plugin and then sell it as a freemium plugin on WordPress.org? | I would normally not answer, but since I answered your other question once please allow me to.
If you check the MIT licensing model you may read:
> MIT licensed software can be integrated into GPL software, but not the other way around.
Since WordPress themes and plugins should be GPLv2 I would say it is possible and legal. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development, licensing"
} |
When importing - failed to import: Invalid post type, feedback
I am attempting to import a site using XML generated by WordPress.com
All the posts and media seem to import, but the comments fail with errors
Failed to import “Sarah Toon - 2015-10-10 08:29:30”: Invalid post type feedback
Failed to import “Kylie - 2015-10-10 08:34:50”: Invalid post type feedback
Failed to import “Sophie Ward - 2015-10-10 08:36:22”: Invalid post type feedback
Reading other posts, here on WordPress.SE none of them have an accepted answer. The closest I could find is Custom post types not imported properly but that is about posts, not comments.
Can someone get me started on solving this please? | The issue is you're trying to import posts with a post type of `feedback`, but there is no such post type registered on your install of WordPress.
Quick-and-easy fix is to register one:
add_action( 'init', function () {
register_post_type( 'feedback', [
'public' => true,
'labels' => [
'singular_name' => 'Feedback',
'name' => 'Feedback',
]
]);
});
Place it in your theme's `functions.php`, or in a MU plugin (eg. `wp-content/mu-plugins/feedback.php`). | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 8,
"tags": "comments, import, xml"
} |
How to use $wpdb to delete in a custom table
I am having trouble finding a good resource on using the $wpdb function.
I am trying to delete a row from a custom table named: eLearning_progress
$removefromdb = $wpdb->query("DELETE FROM eLearning_progress WHERE ID = '$user_id' AND module_id = '$singlecomparearrays_remove'" );
The row I would like to delete has the ID of '$user_id' and the 'module_id' of '$singlecomparearrays_remove'.
I have also tried:
$removefromdb = $wpdb->query( "DELETE FROM eLearning_progress WHERE ID = ($user_id) AND module_id = ($singlecomparearrays_remove)" );
and then:
$removefromdb = $wpdb->query($wpdb->prepare("DELETE FROM eLearning_progress WHERE ID = %s AND module_id = %s", $user_id, $singlecomparearrays_remove));
Please try not to sigh too loudly at my attempts but I can't find a good guide on using the DELETE command with variables in there too. Any help is much appreciated.
Regards, Alex | The best WP API solution for this goal is to use the `delete()` function to remove a row.
A small example, to delete the raw `ID` in the custom table `eLearning_progress`.
$id = 0815;
$table = 'eLearning_progress';
$wpdb->delete( $table, array( 'id' => $id ) );
But I can't see which raw you will delete in your table `eLearning_progress`? Maybe you enhance the question to understand it much better. | stackexchange-wordpress | {
"answer_score": 30,
"question_score": 8,
"tags": "wpdb, sql"
} |
Dynamicaly update field created with wp_editor()
I'm trying to get value of hidden `textarea` created by `wp_editor()` or check if anything is typed it, but the problem is that the value is updated on submit, not dynamically. What I need is to validate with jQuery whether the field is filled in or not.
My field:
$settings = array(
'editor_height' => 300,
'media_buttons' => false,
'teeny' => false,
'quicktags' => false
);
wp_editor( $post->post_content ,'my_content', $settings);
The only idea that I get is:
var name = $('iframe#st_content_ifr').contents().find('#tinymce p').length;
and then count paragraphs, but this solution seems to me a bit silly. Is there any better way? | I have solved the issue with:
jQuery(document).ready(function ($) {
// Check if TinyMCE is active
if (typeof tinyMCE != "undefined") {
$('form').on('click', function () {
if (tinyMCE.activeEditor != null){
var editorContent = tinyMCE.activeEditor.getContent();
$('#get_content').val(editorContent).change();
if ((editorContent === '' || editorContent === null)) {
$('#get_content').val(editorContent).change();
}
}
});
}
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, tinymce, wp editor"
} |
Display author name, outside the loop, if they haven't published a custom post
I'm having trouble trying to display the current logged in author's first_name even if they haven't published a custom post outside the loop. Could someone get me started please. | author's name or logged in user's name?
can use `global $current_user;` or `wp_get_current_user();` if the user is logged in.
if( is_user_logged_in() ) {
$current_user = wp_get_current_user();
echo $current_user->user_firstname;
}
for specific user role you can check `$current_user->roles` array.
Reference:
< < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "author, user meta, publish"
} |
Unable to show a message after plugin activation
Based on: <
My actual code
class Activation {
function __construct() {
add_action(
'admin_notices',
array($this,"text_admin_notices")
);
Utils::update_option("is_activated", true);
}
function text_admin_notices () {
?>
<div class="notice notice-success is-dismissible">
<p> TEST MESSAGE</p>
</div
<?php
}
}
I know that `__construct()` is being executed, because `Utils::update_option` (a simple wrapper) is working, it's creating the option in the option table.
So I expect that the call to `add_action` should show a message to the admin user that is activating my plugin.
Actually, the plugin is beign activated, but no message is shown.
I'm using Wordpress 4.7.1 (a fresh, clean, no-other-stuff, today's installation)
What's wrong in my code? | <?php
/*
Plugin Name: Activation
Description: This display notice message test plugin
Author: Nanhe Kumar
Version: 1.0
Author URI:
*/
class Activation {
public static function init() {
add_action('admin_notices', array(__CLASS__, 'text_admin_notice'));
}
public static function text_admin_notice() {
?>
<div class="notice notice-success is-dismissible">
<p> TEST MESSAGE</p>
</div>
<?php
}
}
add_action('init', array('Activation', 'init'));
Your message not showing because your class constructor is not executing you can test through add die in your constructor then you can better understand what is happening. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, hooks, activation"
} |
WP_Query Excluding pages with Order is 0
I have a custom WP_Query with the following arguments
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'meta_key' => 'tile-home',
'meta_value' => 1,
'orderby' => 'menu_order',
'order' => 'ASC'
);
That selects all the published pages which have the custom field **tile-home** set to **1** and orders them by the page attribute **Order**.
How can I edit the arguments in order (please, forgive me the pun) to exclude all the pages that have menu_order set to 0? | You can define custom `where` like this if your table is `wp_posts`
function _20170112( $where ){
$where = $where . ' AND wp_posts.menu_order > 0 ';
return $where;
}
And sandwich your query with this:
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'meta_key' => 'tile-home',
'meta_value' => 1,
'orderby' => 'menu_order',
'order' => 'ASC'
);
add_filter( 'posts_where', '_20170112' );
$q = new WP_Query($args);
remove_filter( 'posts_where', '_20170112' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp query, exclude, menu order"
} |
How to detect custom query inside `posts_where` hook?
Imagine you have something like this:
function f_posts_where( $where ){
// set a condition based on arguments ...
}
add_filter( 'posts_where', 'f_posts_where' );
What is the best way to set a condition for my custom query inside the `f_posts_where`?
I create a custom query like this:
$q = new \WP_Query( $args ); | If we have the query arguments like this
$args = array(
'queryid' => 'blackjack',
...
);
$q = new WP_Query( $args );
Note we added one custom query argument that is not officially present in here. Now we can identify the exact query by that `queryid` if we use the second parameter of the `posts_where` hook.
function f_posts_where( $where, \WP_Query $q ){
// $q->query will hold the query arguments ...
if ( 'blackjack' == $q->query['queryid'] ){
// do our custom actions on $where for our queryid blackjack
return $where.
}
return $where;
}
add_filter( 'posts_where', 'f_posts_where', 10 , 2 );
As you can note `$q->query` will hold the query arguments.
This will allow us to intercept the custom queries we like if we add custom arguments we like. In this case the `queryid`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "wp query, query"
} |
How to unpublish a page and still keep a draft?
I have a holiday sale page that no longer applies as the holidays have past.
* I want to keep the page for future design reference.
* I do not want the page to be accessible from the Internet.
I tried:
* Setting the page status to `Pending Review`
* Setting the page status to `Draft`
Neither of these status changes seem to have any effect as the page is still visible at the URL. I am not even sure why these settings exist for pages.
I could password protect or set the page to private, but neither option unpublishes the page.
I could do a 301 redirect, but I would prefer not to use this method. (SEO impact of 301 redirects.)
Is there no other option? | > When I logged out the URL generated a 404.
Correct.
> Why can I see the page when logged in? Is this documented somewhere in the codex?
I think this is something that codex has but some parts are still not written, like this part for draft. In the case of **draft** post your permalink will look like this:
?p=2898&preview=true
And it is not available when you are not logged out as you noted -- _404 error page_ is what you will get.
The same error you will get also for the **pending review** status when you are not logged in, but the permalink will be the same as for the **published** post if you are logged in. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "publish, draft, customization"
} |
Cant upload SVG files after updating Wordpress 4.7.1
I updated Wordpress to 4.7.1 and cant upload SVG anymore.
I had a function in my functions.php file
function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
but it also dont help now. | Per the thread below, a **temporary solution** would be to add this code to your wp-config file:
define( 'ALLOW_UNFILTERED_UPLOADS', true );
< | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "svg"
} |
Access saved Options / Settings
For some reason, I am battling to make sense of everything. This is my code on paste bin: <
I want to be able to retrieve the options that are saved in the fields. This does not return anything:
<a href="<?php echo get_option('contact_details_vimeo_render'); ?>" target="_blank">
<i class="fa fa-vimeo" aria-hidden="true"></i>
</a>
I basically want to be able to retrieve the stored data as desired. | Clearly I wasn't thinking :-(
Since all my options/settings are wrapped in a function that's how I need to retrieve them.... Do you get it? Using the function (I mean... hello!).
**_Rough code:_** ` $x = contact_details_telephone_render(); echo $x;`
That will display the telephone number. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "options, settings api"
} |
Skip in Wordpress Post ID's, can this cause issues?
Hoping to get a quick answer to this, couldn't find any existing questions.
Long story short, someone on our system used a Woocommerce product importer plugin and set the Post ID's in the CSV to a random number. We now have a jump in our Post ID's of about 300,000, here's the relevant screenshot from PHPMyAdmin:

Thanks! | As long as the post ID is consistent (value is referenced correctly in post meta table and term relationship table or in any other relevant place) you'll have absolutely no issue. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, woocommerce offtopic"
} |
Identifying where plugins are being used in your wordpress install
I've inherited an existing wordpress installation and there are several plugins (active and inactive) that I'm unfamiliar with and unsure if they're even still being used in any fashion. Once I see that they're not being used at all, I plan to delete them.
Do you have any tips or ways to automatically test if any content using these plugins (and if so, identifying where), without deactivating each, one by one, and examining different pages or the dashboard?
I'm thinking something like searching for plugins' shortcode(s) in my posts tables? | This would be impractically to automate due to nearly endless amount of ways which constitute plugin "use". What plugins do range from super obvious to extremely subtle and niche.
Some plugins specialize in changing behavior to _not_ do something, making their functionality consist of _absence_ rather than presence of results.
If I absolutely _needed_ a starting point I would dump `get_included_files()` and check against plugin folders to have a rough guess which stuff is actively loaded. But that would only serve as rough outlook.
Overall I don’t think you can be off the hook for actually examining _what_ the active plugins are and what their purpose is, then handling case by case. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, testing"
} |
WordPress MultiSite login to the respective site
I would like to have one login form (either wp-login.php or custom) that will allow my users to sign in into their respective site.
For instance:
`www.example.com/site1/` <\-- URL to the sub site
Now I want to have the login form at `www.example.com` where the user can enter `site1` and their password and logs in to their sub site, redirect to their dashboard directly.
Is this possible? Thanks folks. | Apparently, this is how it works already. You can have the user sign in using the main site's wp-login.php.
_In your case just make sure the user is not added to the main site._ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "multisite, login"
} |
Delay the ping to Google when publishing new Posts or Pages
When a Post/Page is published, WP helpfully informs Google about it. But it has happened few times that someone accidentally publishes a product Page before the launch, they of course unpublish it in the same minute, but it's already beamed into Google (if I'm not mistaken). Is there a way add a few minute delay to that?
Related: I know it's possible to add a delay to RSS feed publishing. I've also installed the plugin "Confirm Publishing Actions" which remedies the accidents pretty well. | The pingback functions run via the hoook `do_pings`. The core use the follow default:
`add_action( 'do_pings', 'do_all_pings', 10, 1 );`
This hook is on default a cron job, running in the scheduling as single event of the core.
I think you should remove this hook via `remove_action` and add a custom logic to fire this function later, after your publishing. You can do that via the scheduling functions of the core, like the core functions but with your enhancements to run later as the publish date of the post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pingbacks"
} |
how to make an array of post id's in is_single
For example, the code below only shows the page challenge for post id 2578. However i got 8 other posts that should have the same layout. All others should have the layout from challenge-2 etc. I was hoping i could do that by just adding commas between the ID's. like 2578, 2579, 2580 but that doesnt work. What do i need to do?
if ( is_single( 2578 ) ) {
get_template_part('partials/content', 'challenge');
}
elseif ( is_single( ) ) {
get_template_part('partials/challenge/content', 'challenge-2');
get_template_part('partials/challenge/content', 'categories');
get_template_part('partials/challenge/content', 'snake-checklist');
get_template_part('partials/challenge/content', 'timeline');
}
?>` | You must set it the ids in a array like:
if ( is_single( array( '11717', '11723') ) ) {
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, posts, array, single"
} |
How to get all Custom Post Type Filtered by one Specific Taxonomy Term
I have a custom Post Type called `Movies`, and an associated Taxonomy called `Genre`. Now I need to list all CPT(s) which are in Genre of 'Comedy' in my own custom page (regardless of WP parmalink mechanism)
Following code only returns the custom post type `moviesCPT`:
$args = array( 'post_type' => 'moviesCPT', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) :
$loop->the_post(); the_title();
echo '<div class="entry-content">'; the_content();
echo '</div>';
endwhile;
Can you please let me know how to handle this? | Specify this when you make your query:
'genre' => 'comedy'
Where `genre` is the name of your taxonomy ( not the human readable version, but the internal slug ), and `comedy` is the slug of the term you want to filter by
Importantly, indent your query parameters, and put them each on their own line so that it's easy to read/type/change, a good editor will do this for you. You also need to do an `if( $loop->have_posts() )` to check that you got posts and handle things if none were found, and a `wp_reset_postdata` call to clean up at the end ( otherwise any calls you make will show the last movie in the loop, rather than the current post/page )
You can use the `tax_query` parameter for more complex queries, the details are in the codex under the `WP_Query` documentation | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, taxonomy"
} |
As a plugin developer, how do I remove a plugin from the global plugin directory?
I currently have a plugin in the global WordPress plugin directory that I'd like to remove. It is currently broken, outdated, and I do not intend to provide continuing support for it. To spare people the heartbreak of installing it, I'd like to remove it.
Unfortunately Google is flooded with how to remove plugins installed on WordPress sites, so that makes it hard to find a clear answer for this. | Just delete the content of your plugin directory using subversion in the SVN repository.
svn co your-plugin
In other words, these instructions may help you update the plugin files.
svn status
svn update
svn commit -m "Emptied my plugins..."
If you need to delete files use this
svn st | grep '^!' | awk '{print $2}' | xargs svn delete --force
**Ref.** 1 and 2
* * *
I think you will also need to send an email to plugins at wordpress.org, but they occasionally remove empty directories.
When I first wrote to this email address the great Otto replied. Enjoy. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development"
} |
Getting terms to have space between them
I am trying to show a list of terms that a post is located in. Within the admin it is showing posts in more than one term such as Mixed, Office. My issue is that with the code that I am using it is putting the into my templet but is placing the right next to each other and now adding space between them so it would look like Mixedoffice The code I am using is below. Thank you for any help on this.
<?php $terms = get_the_terms($property['ID'], 'property_sub_type');
if(!empty($terms)){
foreach($terms as $value){
echo $value->name;
}
}
?> | You can either concatenate your call to echo with a space or newline.
**Space:**
<?php $terms = get_the_terms($property['ID'], 'property_sub_type');
if(!empty($terms)){
foreach($terms as $value){
echo $value->name . " ";
}
}
?>
**Newline:**
<?php $terms = get_the_terms($property['ID'], 'property_sub_type');
if(!empty($terms)){
foreach($terms as $value){
echo $value->name . "\n";
}
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "terms"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.