INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How do I apply/target CSS to a specific user role or roles?
How would I apply some front end CSS to a specific user role or roles? | If you're looking for a way to add the roles into the **body class** , like here:
<body class=" ... role-administrator role-jedi role-knight ... ">
then you could try the following:
add_filter( 'body_class', function( $classes )
{
if( is_user_logged_in() )
{
$classes = array_merge(
(array) $classes,
array_map(
function( $class )
{
return 'role-' . $class; // Here we prepend the 'role-' string
},
(array) wp_get_current_user()->roles
)
);
}
return $classes;
} ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "css, user roles, front end"
} |
Customise Excerpt start and end
I am attempting to customise a search result page to display a title and excerpt that contains the search query.
I am using the "Search everything" plugin for this, and I find that sometimes on a more obscure search query, the excerpt displayed in with `get_the_excerpt();` does not contain the search query, as it appears further into the post.
My question is: Can I customise the start index of my excerpt to ensure the search result is within the excerpt, for example:
"... here the except will lead in so find our _search query_ and then lead out again..."
I am working on a site that was built by a colleague who no longer works for the company, so I can't ask him questions, and I would also like to avoid messing around in functions.php and any core functionality, as I don't want to break anything in another section of the site. (as well as my wordpress knowledge is almost non-existent) so I would prefer some kind of page-local based solution.
Thanks | The Search Everything plugin supports "Search Highlighting" in the results page which should produce the results you are looking for.
We have no way of knowing how customized the search results page is in your specific project though. You may find that you are fighting an up hill battle until you (or someone on your team) can dive into the PHP to determine what's going on in there. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "search, excerpt"
} |
JWT authentication with WP - Approach
We're using JWT (JSON Web Token) for authenticating our WordPress application with an external service. The current flow we're thinking of is like this:
1. The user signs in on the the parent site
2. The parent site sends a POST request with the user information and the JWT token to the WordPress site
3. The WP site stores the JWT token
4. The token is checked for expiry every time the user visits a new page, and if the token is expired, the user will be redirected to the parent site for logging in again.
My questions:
1. Is this the right approach?
2. How do I store the JWT token? A cookie? Or in the database, with the user's information as a unique identifier? Note: The users will not be registered on the WP site.
3. How do I check for expiry?
There is a WP plugin for JWT but no documentation for it, hence I am not sure if it will serve my purpose. | This showed up as a notification due to the upvote. Here's how I solved it.
1. The endpoint coded in the app that I am supposed to authenticate with prepares the token.
2. The token has to be in the specified format.
3. It then should be base 64 encoded and hash encrypted.
4. The `wp_init` handler should be used to handle the POST request sent by the endpoint, to extract the token.
5. The key will be shared via some other way, used for decryption.
6. Once the token is extracted, compare it against a locally generated token with the same information.
7. Store it in a cookie, and check it on every page access. You can expire it after a while or keep on increasing the time slice on every page access.
The endpoint could be in any language. Also this is the general flow of it, you can use it anywhere you want. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 8,
"tags": "authentication, single sign on"
} |
rewrites and custom links in page need help with add_rewrite_rule
I have one page with edited permalink, like, `address.com/detail/` I need to send there some values by GET request, so i would like the link looks like `/detail/value1/value2/`
i added this code in
add_action('init', 'rewrite_rules');
function rewrite_rules(){
add_rewrite_tag('%value1%', '([^&]+)');
add_rewrite_tag('%value2%', '([^&]+)');
add_rewrite_rule('detail/([^/]*)/([^/]*)/?$','detail/?value1=$matches[1]&value2=$matches[2]', 'top');
}
but it doesn't work actually, and i can't get which rewrite rule structure i should use to make it works. value1 and value2 was added to wp_query array. may anyone help?
flush_rewrite_rules
didn't help, also | Internal rewrite rules should all point to `index.php`. You also need to set the proper query vars so that the main query can successfully run, in this case, to query for your `detail` page.
add_rewrite_rule(
'detail/([^/]*)/([^/]*)/?$',
'index.php?pagename=detail&value1=$matches[1]&value2=$matches[2]',
'top'
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, url rewriting, forms, rewrite rules"
} |
Disable Garbage Collection?
I have a WP site which creates 500's errors for about 2% of Apache requests (mostly bots and crawlers). I'm not able to stack trace most of those requests with 500's neither to PHP or MySQL errors as well Apache error logs.
Apache access log example for crawlers:
41.79.186.247 - - [06/Oct/2015:11:23:49 -0400] "GET /international-chamber-of-commerce-icc-ud-754/ HTTP/1.1" 500 - " "Mozilla/5.0 (Windows NT 6.2; rv:42.0) Gecko/20100101 Firefox/42.0"
54.193.63.98 - - [06/Oct/2015:11:29:05 -0400] "GET / HTTP/1.1" 500 - "-" "webmon-webagent v1.3"
199.167.17.37 - - [06/Oct/2015:11:39:23 -0400] "GET / HTTP/1.1" 500 - "-" "Mozilla/5.0 (Anturis Agent)"
Is it good idea to disable a garbage collection (`gc_disable()`) for the whole WP site to prevent any memory leak caused by a theme or plugins? | Disabling garbage collection only means that what ever memory is being leaked will reamain leaked and there will be no effort to reclaim it.
To fix 500 problems you need to check the actual errors reported at the php error log. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "optimization, server load, 500 internal error"
} |
Error in meta_query not get result
I have this `WP_Query`
<?php
$args = array(
'post_type' => 'banner',
'posts_per_page' => 25 ,
'meta_query' => array( 'relation' => 'AND',
array('key' => 'ads_status','value' => '1'),
array('key' => 'adsposition','value' => 'top'))
);
$slide = new WP_Query( $args );
if ( $slide->have_posts() ) : while ( $slide->have_posts() ) : $slide->the_post();
$yourfile = get_post_meta(get_the_ID(), 'yourfile', true);
$adsposition = get_post_meta( get_the_ID(),'adsposition', true ); ?>
<img src="<?php echo $yourfile; ?>" width="1350" height="515">
<?php
endwhile; endif;
wp_reset_query();
?>
I have tow meta box (ads_status,adsposition) and its saved good in wp-admin, but in home page not show any result, but when delete `meta_query`, Its work and get me result.
Where the error ?? | Your query seems to be fine and it should work. It's not returning result probably because you are missing `type` parameter for `ads_status` field.
So your code should be.
<?php
$args = array(
'post_type' => 'banner',
'posts_per_page' => 25,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'ads_status',
'value' => '1',
'type' => 'NUMERIC',
),
array(
'key' => 'adsposition',
'value' => 'top',
),
),
);
$slide = new WP_Query( $args );
if ( $slide->have_posts() ) : while ( $slide->have_posts() ) : $slide->the_post();
$yourfile = get_post_meta(get_the_ID(), 'yourfile', true);
$adsposition = get_post_meta( get_the_ID(),'adsposition', true ); ?>
<img src="<?php echo $yourfile; ?>" width="1350" height="515">
<?php
endwhile; endif;
wp_reset_query();
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, meta query"
} |
WP 4.3.1 new install on localhost missing php.ini
I've installed WordPress on my localhost Mac OSX Yosemite box. I'm getting error:
> The uploaded file exceeds the upload_max_filesize directive in php.ini
phpinfo() reports upload_max_filesize = 2M
I noticed that there was no php.ini inside the wp-admin folder of the WordPress default install, so I placed one there with upload_max_filesize = 64M.
I placed the php.ini into the wp-admin directory of the site I'm working. Unfortunately, I still get the error message. And phpinfo() file located in root directory of the site still reports upload_max_filesize = 2M
Any ideas how to resolve? The only other php.ini file I have is under:
private/etc/php.ini.default
I've edited that one to 64M as well, but no change in phpinfo() still.
The WP install is a brand new zip of 4.3.1 from wordpress.org | As you discovered php.ini is not part of WordPress but rather a file that exists in your local environment.
Once you track down the correct php.ini file and make the change to the upload_max_filesize parameter you may need to restart your local Apache instance.
That being said though, I'm not sure the file you mentioned is the correct file since it has the .default extension.
Are you running the native LAMP stack that comes on Yosemite or did you use a third-party tool to get your local environment up and running? Examples of third-party installers include MacPorts, Homebrew, XAMPP, MAMP, manual installs.
Each one is a little different so knowing that bit of info will help you track down the location of your INI file. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "uploads, php.ini"
} |
WP REST API v2. filters doesn't work
I'm using WP REST API v2 to get posts.
When I tried to open localhost/wp-json/wp/v2/posts in my browser I got json with all my posts.
I tried to open localhost/wp-json/wp/v2/posts/?category_name=uncategorized and I got the same json though all my posts assigned to specific categories.
Maybe I'm using wrong filter but I tried to open localhost/wp-json/wp/v2/media?post_parent=15 from first json and got all media on my site instead of one attached to the post
What I'm doing wrong with this? | I found answer here <
add_action( 'rest_api_init', 'add_filter' );
add_filter( 'query_vars', function( $query_vars ) {
$query_vars[] = 'post_parent';
return $query_vars;
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, plugin json api, wp api"
} |
Remove Categories and Tags from Admin Dashboard
I'm using my own taxonomy for blog posts and would like to remove Categories and Tags from the Dashboard. I've removed them from the Admin Menu and the meta boxes on the Edit Posts page from this question here: Remove Categories / Tags From Admin Menu
But now I'm trying to remove it from the All Posts page in the Dashboard where it shows a list of all the posts in a table and across the top are Title, Author, Categories, Tags, Date, etc. I can't seem to find how to do this. | Just like @fatwombat suggested you need to rewrite the table. If you can't modify the @Milo solution, here is a snippet that will remove the columns:
function my_manage_columns( $columns ) {
unset($columns['categories'], $columns['tags']);
return $columns;
}
function my_column_init() {
add_filter( 'manage_posts_columns' , 'my_manage_columns' );
}
add_action( 'admin_init' , 'my_column_init' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "categories, tags, dashboard"
} |
Access methods in plugin template
I'm new to PHP and trying to learn my way through Wordpress. Within my theme's functions.php file, I wanted to access a method available inside bbPress's plugin template.php file. I'm getting `"Unexpected token ['`
Inside bbPress plugin template.php:
function bbp_topic_reply_count( $topic_id = 0, $integer = false ) {
echo bbp_get_topic_reply_count( $topic_id, $integer );
}
I'm accessing this function in my current theme's functions.php:
$count = bbp_topic_reply_count(125);
Do I have to include anything from the plugin (i.e bbpress/template.php)?
Thanks. | Normally not (it depends on what part of the plugins code you want to use and how the plugin initializes itself in the context in which you want to do it), the main plugin files are loaded as part of the wordpress boot process and the convention is that they will load the other files in the plugin at that time, therefor all the function declared in a plugin should be available to use after the boot was finished, and especially in a theme.
The error you are getting is probably just a syntax error in your code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, templates, bbpress"
} |
Redirect blogpage /blog/abcd/ to /blog/
I want to redirect the url if it contains the string like `/blog/abcd.../` to blog listing page i.e. `/blog page`. I used a to code in htaccess file.
`Redirect 301 /blog/abcd
But the browser says `Too many redirect` error. I think Wordpress also do a redirection for blog single post that is `/blog/abcd` to `/abcd`. Can we force htaccess to do redirect if url contains `/blog/` to blog listing page. | I have done it by the following code
RewriteRule /blog/([A-Za-z0-9-]+)/ [NC,L] | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "redirect, htaccess"
} |
How to get only the URL of nextpage (without <a> tag)
Here is my Function
function next_pages( $args = '' ) {
$r = wp_parse_args( $args, $defaults );
extract( $r, EXTR_SKIP );
global $page, $numpages, $multipage, $more, $pagenow;
$output = '';
if ( $multipage ) {
if ( $more ) {
$output .= $before;
$i = $page + 1;
if ( $i <= $numpages && $more ) {
$output .= _wp_link_page( $i );
$output .= $nextpagelink;
}
$output .= $after;
}
}
if ( $echo )
echo $output;
return $output;
}
This includes the outer element, name etc, I want just the link e.g.
Many thanks | If you check out the source of `_wp_link_page`, you'll see all the URL calculations are coded directly within - you can either lift this code straight out into your own function, or sprinkle a little regex around the existing function:
function wpse_204737_get_post_page_url( $i ) {
if ( preg_match( '/href="([^"]+)"/', _wp_link_page( $i ), $match ) )
return $match[1];
}
Worth noting that `_wp_link_page` is a "private" function, and is not intended for use in 3rd party plugins & themes - it _may_ be renamed/removed/deprecated in a subsequent release. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "nextpage"
} |
Update configured themes
**Background:**
We've inherited care of a WP Networks install with many individualized sites. Most of them have some type of directly customized theme. If I begin updating themes, clients will lose customization. We've since disallowed direct theme customization; opting instead for child themes. Going forward we'll be okay; however, I need to tackle these legacy sites.
**Question:**
How might I update themes in place and at the same time save and/or re-implement clients' customization? I will need something that I can automate at some point.
**Brainstorm:**
My first idea was to download the currently running version of their theme from a codeplex and do a diff across both folders. Next activate that unaltered version in the unaltered theme and moving the diff'ed files to a child theme. Once that is in place, I'll issue `wp theme update --all`.
But I still fear this will be a load of manual work. | As per comments, courtesy Matthew, this seems to be the best option:
> I think your brainstorm is the best option. You should get them all child themes and then going forward it will be way less of a hassle to update. It shouldn't take too long. Just figure out which files were customized, through them in a child theme, back up the customized parent theme just in case, and then update the parent theme. Then it should be way better. Not only will you need to do a long manual theme update but in the future you can just update instead of transferring customizations. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "multisite, themes"
} |
How to get the URI to a theme without the domain. Example: /wp-content/themes/my-theme
I basically want the output of `get_stylesheet_directory_uri()`, but without http(s) and the domain. | Use `parse_url()`, because it exists exactly for that reason:
$path = parse_url( get_stylesheet_directory_uri(), PHP_URL_PATH );
Chris Cox’ solution will fail when the `wp-content` directory runs under a different domain than the rest of the site. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "theme development"
} |
Vertical Menu items shifting to same line when window size increased
I've tried messing with float and clear but could get anything to keep this from happening:
 I continue to work off the localhost version.
The sites are identical. I then add some posts and pages and edit the css file. To update the live site, would I just update the database and the css file that was edited? Those were the only things that were edited, but I'm not sure if I have to reconfig the database at all or run some type of refresh or update in the database.
Thanks | If you only changed some CSS, then updating the CSS file on the live server should be sufficient (unless you need to clear a cache or something).
If you changed/created posts on your localhost - then those posts will _not_ be on your live site. You could overwrite the live site's database with your localhost database - however then you will lose any data that was created on the live site (for example, comments).
In general, if the posts/pages you're creating on localhost are supposed to also be on the live site, you're better off creating them there in the first place. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "database, migration, localhost"
} |
To remove rendering of menus and header, plugin or theme?
I need to create a view of my website which does not render the header (where I see my user name) and maybe display just one menu on the side.
Do I achieve this through a plugin or through creating a new theme? | Creating a Page Template is a much simpler way of alternating Page views, creating one is nice and easy:
* Simply copy the `page.php` in your theme, and paste it.
* Rename the file to anything, best practice is: `page-template-something.php`
* Put the following code into the file at the very top:
<?php
/**
* Template Name: My Design
*/
//get_header(); //or do whatever
* Now you can remove everything from the page and redesign however you like.
Copying the existing `page.php` will give a guide on page structure, you can follow that or can create your entirely new view.
### More details:
* **Page Templates** \- WordPress Developer Guide | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, theme development, views"
} |
Sorting users by a field, not by ID
I basically do this now:
$users = get_users();
sort($users);
foreach ( $users as $user ) {
echo '<option>' . $user->companyname . '</option>';
}
Except the sort() function will sort by the ID. How can I change it to sort by my custom field companyname? | By passing orderby and order arguments in array.
`$args = array( 'orderby' => 'login', 'order' => 'ASC', ); get_users( $args );`
**orderby** \- Sort by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', 'post_count', 'include', or 'meta_value' (query must also contain a 'meta_key' - see WP_User_Query).
More details : < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
add_rewrite_rule to pass entire path as a single parameter
I want to rewrite an url and pass the whole path as a parameter. Something like:
www.example.com/csearch/foo1/bar1/foo2/foo3/bar4 => www.example.com/index.php?page_id=23&csearch=foo1/bar1/foo2/foo3/bar4
The script on page_id 23 will parse the content of csearch.
The path after /csearch/ varies in length. It can have 0 or 30 levels.
I have a working solution for only one level
www.example.com/csearch/foo1 => www.example.com/index.php?page_id=23&filter=foo1
works fine with the following added to functions.php
function create_new_url_querystring() {
add_rewrite_rule('^csearch/([a-zA-Z-]*)/?$', 'index.php?page_id=23&filter=$matches[1]', 'top');
}
add_action('init', 'create_new_url_querystring');
I believe I need a new regex to match the entire path, not only the first level.
Any idea on how to solve my problem?
Thanks. | A quick tweak to your regular expression. You are currently capturing only letters before the first /
add_rewrite_rule('^csearch/(.*)$', 'index.php?page_id=23&filter=$matches[1]', 'top');
Note when parsing this that you may or may not have a trailing slash at the end of your value of filter. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "redirect, rewrite rules"
} |
Video script issue, JavaScript attribute remains 'undefined'
I have a project in development and I want to use this technique to load a background video element.
This should load into the large white box below the purple nav bar. So far I have added the script to my `enqueue-scripts.php` file:
wp_enqueue_script( 'video', get_template_directory_uri() . '/assets/js/site/video.js',
array(), '', true );
It seems to be working correctly, as I can see the script `video.js` is listed in the footer.
The problem is when the script runs, the video element doesn't receive the video source attribute correctly and remains 'undefined'.
Any suggestions? | Hard to tell exactly what's happening without checking your code, but if you inspect your home page, you'll see that the video element is being added outside the BODY tag (check attachment below). That might be the reason your script can't find the video source.
.
Is there a way to have WP inject that image into a stylesheet? This doesn't seem possible given the WP loop only residing in the HTML template but I thought somebody might have an idea. | Typically with themes that support custom styles/images, you define everything you can in your stylesheet, and then add the dynamic styles inline:
.header {
background-position: 50% 50%;
background-repeat: no-repeat:
background-size: whatever;
}
And in your templates:
<div class="header"<?php if ( $image ) printf( ' style="background-image: url(%s);"', $image ) ?>>
Title
</div> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "templates, advanced custom fields, media library"
} |
require_once not working
I have a custom page template, and this template need to include one php file. I tried to put this script
require('.../hc-v2-child/ayah.php') and this require(__DIR__.'ayah.php');
in functions.php and in the custom page template, but I'm getting this error
[07-Oct-2015 04:15:21 UTC] PHP Fatal error: require_once(): Failed opening required '/folder/folder1/public_html/folde3/wp-content/themes/hc-v2-childayah.php' (include_path='.:/usr/php/54/usr/lib64:/usr/php/54/usr/share/pear') in /folder/folder1/public_html/folde3/wp-content/themes/hc-v2-child/page-mylogin.php on line 51 | If the file you are trying to include is in child theme folder then try following:
`require(get_stylesheet_directory_uri().'/ayah.php');` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, page template, include"
} |
Subdomain to website directory blog transferring
I have a blog that is located on a subdomain blog.example.com and I have a main website located on example.com. They both use the same wordpress template.
I'd like to transfer my blog from the subdomain to the directory of the example.com preserving 'recent posts', 'categories' and other blog-ish features.
I know that there is a plugin that allows for importing/exporting wordpress posts, but the main question is, how can I transfer those blog-ish features.
Thanks in advance. | You can just copy your blog files to the domain directory, then look in the MySQL database (with phpMyAdmin, say) and change the `siteurl` and `home` rows in the `wp_options` table to correspond to the new URL. Everything will be preserved, you might have to check and fix the often hardcoded paths to images like template logo and stuff. This is the simplest way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, directory, subdomains"
} |
Add "data-" attribute to image links
Is it possible to add an attribute and value to image links?
I currently have:
<a href="#">
<img class="img-responsive aligncenter wp-image-1286 size-full" src="#" alt="..." width="858" height="304">
</a>
and would like to add `data-rel="lightbox-0"` to the link:
<a href="#" data-rel="lightbox-0">
<img class="img-responsive aligncenter wp-image-1286 size-full" src="#" alt="..." width="858" height="304">
</a>
I also need to add the new attribute to images in a specific taxonomy but I think I can figure out that part. | while googling about the same issue I came upon your question and a similar question from the Wordpress forums. You can control the output of the generated code via the image_send_to_editor filter like this:
function filter_image_send_to_editor($html, $id, $caption, $title, $align, $url, $size, $alt) {
$html = sprintf('<a href="#" data-rel="lightbox-0"><img alt="%2$s" src="%1$s" /></a>', esc_attr(esc_url($url)), esc_attr($title));
return $html;
}
add_filter('image_send_to_editor', 'filter_image_send_to_editor', 10, 8);
Original link: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images, hooks, lightbox"
} |
How to create a Wordpress Plugin that has it's own "page"?
I'm learning plugin development and need to create a plugin to display data from a database. I want this plugin to have several separate pages (not insert content into the home page, etc.). Alost like a whole sub-site but all custom code (similar to what bbpress does).
Can anyone suggest sample as to how my plugin can have it's own page(s) at it's own url ?
Newbie thanks ! | One way this is done is to first create shortcodes that generate the content you want to display on your pages.
Then, upon plugin activation, programmatically add your pages (or custom post type if that is more appropriate) and set their content to your shortcodes using wp_insert_post
Now you have a set of pages ready out of the box that your users can use. However, they can still alter the pages or move the content to their own custom pages if they prefer.
Finally, if your plugin requires Knowledge of which page contains which content, make sure you have a setting in your settings panel to assign any custom page the user likes (for example, like how WordPress allows you to set any page to be the home page)
Hope that helps! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development"
} |
Why "?v=hash" is added to my URLs?
I'm new to wordpress, I set up everything, but there's something that bothers me: on every single URL or link, there's a "?v=hash" appended everywhere (example.com/?v=d21feabed96b).
I tried to see inspect every plugin, I don't understand how this parameter is added.
It looks like it's added in js, because if I see the source, there's no trace of this hash, but I can see in firebug live source.
Plugins installed:
* jetpack
* sumome
* wp-piwik
* wp super cache
* woocommerce
Theme: Storefront
I tried to disable everything, but still I get this hash, does anyone knows how and why it's added?
I'm also using cloudflare | It was woocommerce, it has a setting "geolocalize users with cache support" which adds this parameter to every single url and link. I noticed that the hash appended was the same in every browser on my computer, so I realized it wasn't a "session" hash, but an IP address hash. | stackexchange-wordpress | {
"answer_score": 49,
"question_score": 25,
"tags": "urls, parameter"
} |
do_action in conditional
I'm using the "inbox-status" plugin. I can use this to display unread emails.
<?php do_action( 'inbox_status_count', 'inbox-unread' ); ?>
I want to use this code in a conditional. Only the number of emails shown if more than one.
if ( 0 < did_action( 'inbox_status_count', 'inbox-unread' ) )
echo "<span class='new badge'>";
echo do_action( 'inbox_status_count', 'inbox-unread' );
echo "</span>";
Why don't work? | Note that `did_action` only takes **one** input argument: _the name of the action hook_.
The scope of your `if` sentence is also unclear.
I don't think you want to use `did_action` at all here, it doesn't give you the number of emails.
You can try the following instead:
if ( $unread = do_shortcode( '[input-unread]' ) )
printf( "<span class='new badge'>%s</span>", $unread );
or skip the expensive `do_shortcode` parsing by using the shortcode callback directly:
if(
class_exists( 'IS_Inbox_Status' )
&& $unread = IS_Inbox_Status::get_instance()->get_count( 'inbox-unread' )
)
printf( "<span class='new badge'>%s</span>", $unread );
Note that this is untested. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, conditional content"
} |
User permissions to upload images
I added TinyMCE editor to fronend page via wp_editor() function. I am trying to give user ability to upload images via "Add Media" button in that editor.
Which permissions should I give to user for he have ability to upload images?
This user should have ability to edit/delete his uploaded images, and should not be able to edit/delete other users images. | Only logged in user can upload media from front end. Below code will allow users to see only their media files and not others. Put this in your theme's functions.php file. I hope this helps.
add_action( 'pre_get_posts', 'users_own_attachments');
function users_own_attachments( $wp_query_obj )
{
global $current_user, $pagenow;
if ( $pagenow == 'upload.php' || ( $pagenow == 'admin-ajax.php' && !empty( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'query-attachments' ) ) {
$wp_query_obj->set( 'author', $current_user->ID );
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "uploads, permissions"
} |
Hide post title input for all roles except admin
How would this function need to be updated to exclude the admin?
add_action('admin_init', 'wpse_110427_hide_title');
function wpse_110427_hide_title() {
if (current_user_can('subscriber'))
remove_post_type_support('post', 'title');
}
Remove post title input from edit page | I tried following code and its working. You need to place this in your theme's `funtions.php` file. Let me know how it goes :)
add_action('admin_init', 'admin_only_post_title');
function admin_only_post_title() {
if (!current_user_can('manage_options'))
remove_post_type_support('post', 'title');
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, post meta, actions, title, customization"
} |
Is there a way to change wordpress image resize settings?
Websites nowadays tend to have big banners and big images. Thus when developing sites we try to optimize these images as much as possible. However, when wordpress resizes these images, it does a terrible job at keeping the file size small.
For instance:
I have a 2400 x 1850 px image - at 384 kb (optimized) When wordpress resizes this image down 2048 x 1536 (using add_image_size()) the file size actually grows to over 1.5 MB.
Is there a way to change the settings, whether it's quality or sharpness of the resized image?
I know that there are other plugins out there that will optimize images for you, but most of them wont deal with large sizes unless you pay some monthly fee.
Other plugins only deal with lossless resizing. Which at 2400 pixel is not ideal. At 2400 pixels I can trade some loss in quality for smaller file sizes. | The file size increase you describe sounds odd. Are you referring to jpegs?
Anyway, you can control loss quality for jpegs. Add this to your functions file:
add_filter( 'jpeg_quality', create_function( '', 'return 80;' ) );
Replacing 80 with whatever percentage you would prefer. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images"
} |
Open editor post in a popup
I use this code to open the popup editor.
<script>
function edit() {
var pop = window.open(' <?php echo get_edit_post_link(); ?> ', '_blank', 'screenX=200,screenY=200,width=1000,height=600');
}
</script>
<a href="" onclick="edit()" >Edit</a>
This returns this url: `
But it shows: `
The problems is this "%amp;"
Any solution? | You need to tell `get_edit_post_link` to not use the ampersands as specified in the codex. Try this instead:
var pop = window.open(' <?php echo get_edit_post_link(get_the_ID(), ''); ?> ', '_blank', 'screenX=200,screenY=200,width=1000,height=600'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "urls, editor"
} |
Allow 'Set featured images' to select multiple images
So 'Featured image' option on WP is lacking. What I was expecting is when user selects multiple images it echos out multiple images on the page, instead you can only select one photo. I tried to find some plugin to do **exactly** that, but no luck. It seems easy to do and I wouldn't like any additional plugins.
Can anybody do that so when I type
`<?php the_post_thumbnails('index-thumb'); ?>`
it returns:
<img src="..."...
<img src="..."...
Any help is much appreciated! Thank you! ;) | Its certainly not a few liner code. So its better to use a Feature Gallery plugin. I just tried that which works perfectly fine and you can use below code to get the images in Featured Gallery.
<?php $galleryArray = get_post_gallery_ids($post->ID);
foreach ($galleryArray as $id) { ?>
<img src="<?php echo wp_get_attachment_url( $id ); ?>">
<?php }?>
Please refer plugin description to get more details about the code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails, thumbnails"
} |
How to remove all styles for certain page template?
I know how to create child themes and page templates. I have a child theme of Salient called Salient-Child, and I have a page template called blankPage.php.
For all pages that use this template, I want there to be no CSS loaded at all.
I'm aware of `wp_register_script, wp_deregister_script, wp_deregister_style, wp_dequeue_style`, etc, but I'm not sure where/how to use them.
I've tried typing some of those functions within blankPage.php itself, and I've also tried editing functions.php. I've tried using a conditional with `if(is_page_template('blankPage.php')){...}`.
Any guidance would be appreciated.
Thanks! | I seemed to solve the problem, and it was so simple that I'm shocked I've never seen this mentioned by anyone before.
First, I deleted my entire child theme so that I could start over from a fresh place.
Then, I used < to create a brand new child theme of Salient.
Then, in the **Appearance > Editor** menu, I viewed the `functions.php` file and noticed that it had pregenerated `add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );` and `function theme_enqueue_styles()` for me.
So I simply wrapped the contents of the function within `if ( !is_page_template( 'rawHtmlPage.php' ) ) { ...}`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 5,
"tags": "page template, css"
} |
From where is archive.php getting its posts?
My archive.php starts like this:
get_header(); ?>
<?php if( have_posts() ): ?>
<div id="container" class="portfolio-wrapper">
<?php while( have_posts() ): the_post(); ?>
I'm curious... where is the actual WP Query made? For example when I press on a Category or on an Archive link, I get to this page, but where's the actual select done?
More specifically, I'm curious where the first query is created (in what file), since the above only **uses** a query which was already made somewhere.
I'm asking because I want to create a custom archive (using a shortcode with posts ids in it) and I want to decide what is the best approach to do that :). | The main query is set up by `WP` class (curiously little known, since there is rarely reason to mess with it). It happens in between WP core finishing load and proceeding to load template, in `wp-blog-header.php`.
Note that some nuances of implementation:
* `WP` class works on a global, set up _earlier_ in `wp-settings.php`
* the global it works on is `$wp_the_query`, which acts at _original_ instance from which more commonly used `$wp_query` is spawned. This two-variable implementation is used for detection if the main query had been modified, among other things. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, archives"
} |
How much worse is querying custom fields compared to custom taxonomies, quantitatively
OK, I know (because i've read it many times) why custom fields is less efficient than custom taxonomies when it comes to querying/filtering posts, but just how inefficient is it by comparison? I'd love some researched quantitative statistics to back this up.
What sort of number of posts and custom fields are we talking about before my website collapses? | The trouble with meta queries is they require an additional join _per filter_. Say you have a property site, and you're searching by location, rooms and price. That's three joins. If you were using taxonomies, just two (`terms` and `term_taxonomy`) - no matter how many filters.
The other reason taxonomies tend to beat meta queries is their db schema. They're well indexed and optimised for searching - the meta table, whilst indexed on meta keys, has a value field that's large text - start querying on that bad boy (especially `LIKE` statements) and MySQL will have to take a breath or two.
Having said all that, meta queries have their place and can be extremely useful (with caution). And to be honest, unless you've got **thousands** of posts, or you're applying several meta queries, the difference will probably be negligible. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -2,
"tags": "custom taxonomy, custom field, query posts"
} |
Get all images in uploads directory and list them
I'm trying to get all of the images inside a specific sub-directory within the WordPress uploads directory, and then output all of those images.
$upload_dir = wp_upload_dir();
$logo_dir = ( $upload_dir['baseurl'] . '/logos/' );
echo $logo_dir . '-----<br />';
$images = glob( $logo_dir . "*.PNG" );
foreach( $images as $image ) {
echo $image;
}
`$logo_dir` is outputting the correct directory. I'm not sure what I'm doing wrong with the foreach. | `$upload_dir['baseurl']` should be `$upload_dir['basedir']`. You want the server path, not the URL of the directory. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "uploads"
} |
Integrate WooCommerce theme with a Wordpress theme
I have some questions about WooCommerce theme's integration into an existing Wordpress theme:
1. Is it possible to integrate a WooCommerce theme into an existing Wordpress theme?
2. Should I make my theme supporting WooCommerce since the project's start or can I add WooCommerce integration to my theme in a second step?
3. What are the steps for integrate WooCommerce into an existing theme? Is it possible or I will have to rebuild the whole theme from scratch?
4. What problems could I meet if I will add it in a later time? | I would add it from the start so you don't have to go back to it, and it's a really simple process of creating a woocommerce.php file in your theme and then add the following to your functions.php
add_action( 'after_setup_theme', 'woocommerce_support' );
function woocommerce_support() {
add_theme_support( 'woocommerce' );
}
To create the woocommerce.php, copy your page.php, remove the loop code and replace with:
<?php woocommerce_content(); ?>
More info at < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "theme development, customization, themes, woocommerce offtopic"
} |
A Comma Between Each Items Except the Last One with get_the_term_list
I search here and on Google and I can't find answer to my question, just hope you will find it relevant.
I'm doing a magazine website and I need to display names of contributors as a byline. I'm taking the information from the taxonomy 'Contributor' to display their names.
<?php echo get_the_term_list( $post->ID , 'contributors', 'By ',' and '); ?>
That gives me, By contributor1 and contributor2 and contributor3 and contributor4
But I would like to have something like that instead:
**By contributor1, contributor2, contributor3 and contributor4**
Maybe it's not possible, let me know.
Thanks in advance,
François | `get_the_term_list` uses `get_the_terms` to fetch the term objects. You can use that function instead and build the list however you'd like. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "terms"
} |
What is the CODEX intercept for wp-login.php?action=lostpassword
I want to write a plugin hook for `wp-login.php?action=lostpassword`.
Does anyone know what the add_action() is for `wp-login.php?action=lostpassword`?
I searched the CODEX and could not discover it.
Thank you. | The login form actions are located in `wp-login.php` here and here.
// "login_form_{$action}"
login_form_lostpassword
login_form_postpass
login_form_logout
lostpassword_form
resetpass_form
register_form
There's also the general `login_init` which will fire for all actions.
To enqueue scripts on login, use `login_enqueue_scripts`. Right after that, `login_head` will allow you to add custom meta tags, etc. to the `<head>`.
The end of the page is injectable with `login_footer`.
* If you need to adjust (or add) errors, use `lostpassword_post`, which comes with an argument `\WP_Error $errors`.
* If it's about passwords, you can use `validate_password_reset` which has two arguments, first again the `\WP_Error $errors` and the current `\WP_User $user` as second (or another `\WP_Error` in case the user is errornous). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp login form, password"
} |
Using page template to fetch posts in page
i want to display posts in wp page. to do that this is what i did i created a template named mypage-page.php and copied code from page.php to mypage-page.php
this is my mypage-page.php
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ;?></h2>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, no posts to list</p>
<?php endif; ?>
</main><!-- .site-main -->
// this has header and footer as well .
now i created a page mytest using this template ,what i expect it should list posts but it does not, please help me to understand where i'm wrong . i'm just a beginner | You will want to use wp_query to query the database for the posts, which will be something like:
<?php
$blog_args = array(
'post_type' => 'post',
'posts_per_page' => '-1',
'order' => 'DESC'
);
$blog_query = new WP_Query($blog_args);
while ( $blog_query->have_posts() ) {
$blog_query->the_post();
echo '<a href="'.get_permalink().'">'.get_the_title().'</a>';
}
wp_reset_postdata();
?>
That will display all posts with just the post title, you would need to add pagination and add more detail to the actual displayed element but should give you a head start | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, loop"
} |
get_the_content_feed with paginated posts
I have a wordpress site and i have been working on it's feed. I noticed that when a post has been paginated with , it only renders the first page of the post. What i need to do is get all the content of the post and not just the first page.
while( have_posts()) : the_post();
?>
<item>
<title><?php the_title_rss(); ?></title>
<link><?php the_permalink_rss() ?></link>
<comments><?php comments_link_feed(); ?></comments>
<pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate>
<dc:creator><![CDATA[<?php the_author(); ?>]]></dc:creator>
<?php
$pub_date= mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false);
......
$description = get_post(get_post_thumbnail_id())->post_content; // The Description
$content = get_the_content_feed('rss2');
Any advice? | If you are talking about paginated posts which created using `<!--nextpage-->` tag, then you will have to use `the_content_feed` hook to strip that tag and pass the full content. I have tried below code & it does exactly that. But please note it will pass full content to RSS feed for all the posts.
`add_action('the_content_feed', 'strip_nextpage_tag_for_rss'); function strip_nextpage_tag_for_rss() { global $post; $content = apply_filters('the_content', $post->post_content); $content = str_replace( "\n<!--nextpage-->\n", '', $content ); $content = str_replace( "\n<!--nextpage-->", '', $content ); $content = str_replace( "<!--nextpage-->\n", '', $content ); $content = str_replace( "<!--nextpage-->", '', $content ); $content = str_replace( "<p><!–nextpage–></p>", '', $content ); $content = str_replace( "<p><!--nextpage--></p>", '', $content ); return $content; }`
Place above code in your theme's functions.php file. I hope this helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, feed, paginate links"
} |
Can URL remain the same if migrating from Drupal?
I would like to migrate from Drupal 6 to WordPress.
The article URL in Drupal is: `example.com/node/230`
If I migrate to WordPress, can the URL be the same? | yes, but:
1. it might be hard if drupal mixes several types of content under the /node/ parent.
2. Those are not very SEO or even human freindly URLs so you might actually want to change them and just have a redirect from the old one to the new one. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "urls"
} |
Display child pages in a parent page?
I have a "News" page with child pages and I want to display those child pages in "News" page only, like this
How can I achieve this? | I believe you're looking for this: `get_page_children()`
That function will return an array of your sub-pages, which you can iterate through to display your list. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "pages, child pages"
} |
Show Header When Not In Iframe
On our companies website, we have a list of products, then when you click on a product, a popup opens with the product details. Because this was a popup (in a lightbox) I created a `single-productpopup.php` and removed the header and footer.
The problem I have now, is that the Products are showing up in the Sitemap, and therefore search engines (and this is what we want), but when the link is clicked, the `single-productpopup.php` is loaded, and this doesn't have a header or footer, so the visitor has no way to continue navigating around the site.
What I'm hoping is is there a way to detect if the page is being loaded in an iframe, and so do an if statement something like `if page is not in iframe show header and footer`
Or is there a more practical way to do this, maybe with different php files?
Edit: After thought - or add the header and footer with `display: none` by default, and use javascript/jquery to change that? | I solved this by adding the header php code, and the setting it with display none as below:
#main-header {
display:none;
}
Then using JQuery I added the following:
<script>
if(self==window.top)
{
$( "header#main-header" ).css( "display", "inherit" );
$( "div#mce_height" ).css( "margin-top", "100px" );
}
</script>
This detects if it is in an iframe, and if it's not, it will show the header | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, headers, footer"
} |
How to get product count with respect to categories in WooComerce
Hi I want to display all the categories of products in a loop to display them in category menu along the numbers of products each category contains. Some thing like that
;
$product_categories = get_terms( 'product_cat', $args );
foreach( $product_categories as $cat ) { echo $cat->name; }
But I want to know how to display products numbers in each category. | You just need to add `$cat->count` to get the count of all products in that category. Hope this helps you out.
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms( 'product_cat', $args );
foreach( $product_categories as $cat ) {
echo $cat->name.' ('.$cat->count.')';
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "categories, woocommerce offtopic"
} |
Modify WooCommerce email shipping text value
I'm attempting to use the 'woocommerce_order_shipping_to_display' filter to show 'Free' in the WooCommerce email table when no shipping charges will be incurred. In the image, I'm trying to get the 'Free' and 'Flat Rate' values to just show as free. My PHP is only moderate, but I can't get my code quite there. Does anyone see what I could be missing?
/* return custom text on email when shipping is free */
function filter_email_shipping_text( $shipping ) {
if ( $this->order_shipping != 0) ) {
$shipping = __( 'Free!', 'woocommerce' );
return $shipping;
} else {
return $shipping;
}
}
add_filter( 'woocommerce_order_shipping_to_display', 'filter_email_shipping_text', 1 );
;
function filter_email_shipping_text( $shipping, $order_id ) {
global $woocommerce, $post;
$order = new WC_Order( $order_id );
if ( $order->order_shipping == 0 ) {
$shipping = sprintf(__( 'Free!', 'woocommerce' ));
}
return $shipping;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, woocommerce offtopic"
} |
WordPress RSS feed?
We just started our new blog and we need to submit our RSS feed to some directories, but we do not know what is our new site RSS feed.
Do we need to install any plugin or tool to generate RSS feed?
If feed is already generated by WordPress, where we can find our RSS feed url/link?
This is our website < | If you check the source of the website, you can see two links (CTRL+U to view source):
<link rel="alternate" type="application/rss+xml" title="Scoopaper » Feed" href=" />
<link rel="alternate" type="application/rss+xml" title="Scoopaper » Comments Feed" href=" />
Which means you have: < and < (if comments are open it will display a RSS feed of the comments) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rss, feed"
} |
Store the wordpress "featured image" under »wp_posts« Database table
How to store the WordPress featured image under the `wp_posts` table. Can any one help me?
The reason why I am asking same table details (`wp_posts`), is because I am using a JSON response to add in my android application. So I would like to save featured image also under `wp_posts` table.
;
Be sure though that you update all your posts (re-publish) so that it will have the key value that you specified. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, query"
} |
shop page with all categories with paginate
I am very new in wordpress theme development. how can i make page template for my store page where my all categories listed with 6 to 10 latest post with that category and category name has a link to category page `category.php` **for example:**
in store page
**category 1**
1. first item with this category
2. second item with this category
3. third item with this category
4. forth item with this category
**category 2**
1. first item with this category
2. second item with this category
3. third item with this category
4. forth item with this category
**category 3**
1. first item with this category
2. second item with this category
3. third item with this category
4. forth item with this category
**and so on**
thanks in advance | i think it is petty straightforward solution
first get your all categories list by help of `get_categories()` function and loop though and find the post relative with that.
<?php
$categories = get_categories(); return all categories
foreach( $categories as $cat ){
$query = new WP_query(['cat'=>$cat->term_id, 'postes_per_page'=> 10]);
if( $query->have_postes() ){
echo $cate-name; // this this category name
while( $query -> have_postes() ) {
// show your all post relavent to this category..
}
}
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "categories"
} |
Custom User meta field display
I'm using PODS plugin (< to extend main types in wp and WP Tiles for tiles rendering (< I'v already added field position to user type (it's meta). And i try to call it so (in Text-Only Byline Template):
<span class="author-name">%author%</span>
<span class="author-position">%meta:position</span>
but it render's me:
admin %meta:position
what i do wrong, and how to display this custom User meta fields? | In the second line you forgot the closing `%` after `meta:position` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, custom field, users, pods framework"
} |
How do I make the most minimal vanilla theme possible with nothing but raw content?
I have two themes. One is the full blown already completed theme. With the second theme I only want to show the contents or custom field contents of the post. Absolutely nothing else.
I thought this would be easy but there are 755 files in the theme that I copied. I just want a theme with one or two pages.
How do I make a theme with nothing but content? I'm talking no html, no css, no markup, just raw data.
URL's would work like this
www.mysite.com/myblog/ ---> list of only posts content
www.mysite.com/myblog/?postId=100 ---> only content of post id 100 | The most minimal theme possible has two files: `style.css` and `index.php`.
**`style.css`**
/* Theme Name: Bare-bones theme*/
**`index.php`**
<?php
if( have_posts() ) {
while( have_posts() ) {
the_post();
the_content();
}
}
I'm not sure you could make it more "vanilla" than that. Keep in mind that any HTML markup within the post's content will still be returned.
See Theme Development for more information, or the WP REST API plugin for an alternative approach to returning data without additional markup. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "theme development, themes"
} |
How can I use CURLOPT_USERPWD in wp_remote_post?
I'm trying to setup a proper cURL call in WordPress so am using wp_remote_post(). However, I'm having trouble authenticating the user via wp_remote_post(). Any idea how to convert the following to be used in wp_remote_post?
`curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");`
Full example of proper cURL basic auth is here. | Use the `Authorization` header. Example:
$auth = base64_encode( $username . ':' . $password );
$args = [
'headers' => [
'Authorization' => "Basic $auth"
],
'body' => $body,
];
$response = wp_remote_post( $url, $args );
$response_body = wp_remote_retrieve_body( $response ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "headers, authentication, http, curl, wp remote post"
} |
Internal Stylesheet in Wordpress Theme development
I'm almost done creating my own wordpress theme and it will be my first theme that I'll be submitting to wordpress.org
I have used internal CSS in many pages because the styling is used for a particular post type. Is internal CSS allowed while developing a theme for wordpress? Or is there a strict rule that all the style must be a part of an external stylesheet only? | This will not work when submitting your theme to **wordpress.org** , and this is one of the first things the theme reviewer will tell you to fix (I'm not even sure if these styles will pass the **Theme Check** test).
For every CSS style, fonts, additional scripts, etc., before sending your theme to wordpress.org for a review, you will **have to** enqueue these in your theme to pass the review. No exceptions. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "theme development, css"
} |
How to extract one field from wp_get_post_terms objects?
I know I can get an array of term objects with this line:
$terms = wp_get_post_terms($post->ID, 'mytaxonomy', array('fields' => 'all'));
Or, I can get a simple array of term names with this:
$term_names = wp_get_post_terms($post->ID, 'mytaxonomy', array('fields' => 'names'));
But I don't know how to extract just the names from the array of objects ($terms). This is so I don't have to call `wp_get_post_terms` several times. | `$terms` is an array of objects. You must select one of the array entries before you can reference its properties (fields).
This will print the 'name' of the first object (index zero):
if ($terms) {
echo $terms[0]->name;
}
This will print all the 'name' fields:
if ($terms) {
foreach( $terms as $term )
echo $term->name;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "terms"
} |
New functions in separate directory -- better, portable way
I am just now learning WordPress theming as I have time.
Currently I have a bunch of overrides for many woocommerce defaults in my theme I have:
// CUSTOM FUNCTIONS
require get_template_directory() . '/woocommerce/storefunctions/woocommerce-overrides.php';
Is there a way to do this that is more portable? Such as if I want to change themes how can I avoid adding in the functions.php file for every theme I want to try/fiddle with. I don't know what to search for, so the question: what have I tried is: nothing. | I'd say that the thing you're looking for is **having functions.php as a plugin**. This makes it portable, regardless of the theme you are using. The most simple way is create a new file (something like my-woocommerce-functions.php) and start with the following:
<?php
/**
* Plugin Name: My Custom WooCommerce Functions
* Plugin URI:
* Description: My Custom WooCommerce Functions
* Author: Your Name
* Author URI:
* Version: 1.0.0
*/
/* Place custom code below this line. */
require get_template_directory() . '/woocommerce/storefunctions/woocommerce-overrides.php';
?>
Now you have a plugin which you can activate and deactivate from dashboard. You would have to take care about file paths only (if not using get_template_directory() function). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions"
} |
How does WP decide how to display a page
I am new to WP. I tried reading up as much as I possibly can online, and via browsing through the files. As far as I can tell, no physical pages/links are stored on the disk, so when a page is created, the data is stored in the wp_posts table, and the post metadata is in the wp_postmeta table. My questions are:
1. I am assuming that nothing is stored to disk, with the exception of uploads that go into the wp-contents/uploads directory. Is this correct?
2. Are there any other tables involved in the posts? as in, if I delete the post from the wp_posts and all relevant data from the wp_postmeta, does that get rid of the post?
3. How does WP know if this is a page or a post? which table is that info stored in?
4. Are the wp_comments and wp_commentmeta tables the only tables involved in comments. As in, if I write as script to delete a comment from this table, along with its metadata, will that completely eliminate the post? | Wordpress has a predefined folder structure and runs on a database with a clearly defined structure. The description of the tables and the relationship between them is defined.
1. You can store on the disk the plugins as well as the content that goes into /uploads, like you've mentioned.
2. Yes, it should get rid of the post.
3. in `wp_pages` table in the field `post_type`. You might find the template hierarchy also useful, with this you can customize posts, pages, categories etc
4. Yes, it should get rid of the comments | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, comments, post meta, comment meta"
} |
How do I disable certain menu in editor user administrator page
How do I disable the **media** , **pages** , **comments** , **profile** and **tools** in editor user administrator page?

{
global $menu;
global $current_user;
get_currentuserinfo();
if($current_user->user_level < 10)
{
$restricted = array(__('Pages'),
__('Media'),
__('Comments'),
__('Tools'),
);
end ($menu);
while (prev($menu)){
$value = explode(' ',$menu[key($menu)][0]);
if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
}// end while
}// end if
}
add_action('admin_menu', 'remove_editor_menus'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin menu"
} |
Change public post to private
I posted some items that I only wanted invited family and friends to see. But these mistakenly were posted publically. How do I remove these from public viewing? | There are many ways to do this with plugins or PHP. To do it without any modification to the system, you should mark the post's visibility as "Private" and then only Admins or Editors can see it. You must in this case, make your friends and family "editors", which you can do in the "Users" tab in the Dashboard. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "privacy"
} |
Wordpress theme layout problem
In Drupal, we have blocks to customise the layout.
I am new in Wordpress, if I want to change my layout to the second image.
What should I do? Does wordpress have block region that can know how does the theme region looks like?
; ?>
**Parameters**
> $path: (optional) Path to be appended to the site url.
>
> $scheme: (optional) Context for the protocol for the url returned. Setting $scheme will override the default context. Allowed values are 'http', 'https', 'login', 'login_post', 'admin', or 'relative'.
It simply overrides the default parameters in URL.
For example if you have a website URL like ` (without https) and you want to add https URL on a specific link instead of http, then you use `$scheme` parameter. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "site url"
} |
Migrate site from WordPress multisite to another WordPress multisite
I'm wanting to migrate a site from one WordPress multisite install (Dev) to another (Staging). I've read these posts
How to migrate Wordpress Blogs into Multisite without using the GUI-Import/Export Feature which is about migrating a single site (rather than a site in an existing multisite)
and this one Copy site from one multisite to another which doesn't do a complete job (i.e. you have to deal with menus, etc separately).
Any improvements on either of these answers for migrating a site from one WordPress multisite install to another. | I recommend using Search & Replace DB by Interconnect:
<
Using this tool will let you completely replace the URLs in the database and still maintain the entries as serialized data. This isn't specific to multisite but it should work the exact same way. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "multisite, import, export"
} |
Remove Shortcode [...] from Blog Preview
When utilizing shortcode (plugin, etc.) near the top of the page, the plugin shortcode displays in the preview. Is there a way to hide text within brackets [text like this] from a preview on a recent posts type of page?
The following example shows the shortcode within a blog post preview:
` and add this:
<?php
$content=get_the_content();
$content = preg_replace('#\[[^\]]+\]#', '',$content);
echo apply_filters('the_content', $content);
?>
That is regular expression added inside content. This regex will remove all tags inside content. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, shortcode"
} |
Use Google authentication for pages within a website
We are trying to restrict certain pages of our website, and we use Google Apps for Business, so we were hoping we could leverage Google authentication. Everything I've found on the topic though is specific to using Google authentication to access WordPress (say as a site admin). We are just trying to restrict pages of our published site. Is this possible? | If you can use google authentication to connect as admin, then accessing published site pages are no different than connecting to a different user role.
Make a new user role (say subscriber) and make your pages accessible to that particular role based users only. Make sure they don't have access to anything else than these pages only, if you don't want them to see anything else like certain wp admin features etc. Then connecting to any user within this rule using google authentication will fill your need/target.
If you are new to custom user roles, there are plenty of plugins in WordPress plugin directory supporting user role creation/modification | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "security"
} |
Wordpress functions.php does not affect the theme menus
I am trying to customize my pre bought theme. What i try is, to have different menus for each page without using a plugin. Original theme has a function about navigation which uses walker class. here is the file in the original.entrepreneur theme. <
I use Entrepreneur Child Theme. I want to use primary navigation in home page and turkish navigation in turkish flag. I added functions.php and I added the code below:
if (is_page('AOE Home')){
wp_nav_menu(array('menu'=>'Primary Navigation' ));
} elseif (is_page('turkish')) {
echo "text";
wp_nav_menu(array('menu'=>'Turkish Navigation' ));
}
But navigation elements stays same. Can you help me to solve my problem?
Thanks | Try with adding this code into **header.php** , where menu usually appears. In functions.php you can declare custom menus, but you are **calling** them in header.php or wherever you want menus to appear.
Function **register_nav_menus()** declares menus and should go into functions.php, while **wp_nav_menu()** outputs menus you declared anywhere on the page (so not inside functions.php). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, navigation"
} |
Set a static front-page as a landing page programmatically
I am in process to create my first wordpress theme with underscores.me skeleton, the theme i would like to create its a business theme so when my theme is activated to land directly to a static front-page instead of the default wp posts. How could i do this programmatically and where to put this code (for example at functions.php file) and where to call it. I know i could change this from wp dashboard but instead i would like to do it programmatically and if a user wants to display wp post as the home page to be able to do it from wp dashboard. | You can do it by targeting `get_option('show_on_front');`
some code which could help would be:
function themename_after_setup_theme() {
$site_type = get_option('show_on_front');
if($site_type == 'posts') {
update_option( 'show_on_front', 'page' );
update_option( 'page_for_posts', 'page-name' );
}
}
add_action( 'after_setup_theme', 'themename_after_setup_theme' );
This will run on theme activation only, remember to change the page-name to the page you want to be set as the homepage.
This isn't tested but have used this on a similar project before | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, frontpage"
} |
Load widget only on blog posts
I am attempting to ensure a widget is only loaded on blog post pages.
I tried using `$post_type = get_post_type( $post_id );` inside the widget function of my widget class. However, upon loading pages like the homepage, 'archives', 'categories' etc. . . the post type is always 'post'. The only exception is when I create a page, it returns 'page' as expected.
Is there a way to actually ensure the current page is a post? | I think you're looking for is_single():
if ( is_single() ) {
// Do widget, which will only appear on single-post templates
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, widgets"
} |
Posts - display all posts except a post by an ID
I want to be able to display all posts except a the most recent post which I am doing as follows:-
$last = wp_get_recent_posts( '1');
$last_id = $last['0']['ID'];
echo $last_id; //1477
$args = array('posts_per_page' => 5,
'post__not_in' => array($last_id),
);
$recent_posts = get_posts('numberposts=10&exclude='. $post_id .'"');
if($recent_posts) { ?>
<ul>
<?php foreach( $recent_posts as $recent ) { ?>
<li>
<a href="<?php echo get_permalink($recent->ID); ?>"><?php echo $recent->post_title; ?></a>
</li>
<?php } ?>
</ul>
<?php } ?>
`$last_id` contains the correct value for the most recent post, but the code is still displaying the ten most recent posts without excluding any.
Any ideas? | Couple of issues here
* IIRC, `exclude` should be an array of ID's as `exclude` get passed to `WP_Query` as `post_not_in`
* You are defining arguments which you don't use. You could have simply passed that to `get_posts`. Rememeber, all parameters in `WP_Query` is available as is to `get_posts` as `get_posts` uses `WP_Query`
* You can simply use `'offset' => 1,` to skip the most recent post. You are running total unnecesarry queries here which slows your page down
You can try the following
$args = [
'posts_per_page' => 5,
'offset' => 1
];
$recent_posts = get_posts( $args ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, query posts"
} |
How to Customize Polylang Language Items
I am using Polylang plugin with WordPress 4.3.1, Can you please let me know if there is a way to display language items in short abbriviation like `En` for `English` or `CH` for `Chinese`
I am using this code to display the active languages
<?php pll_the_languages();?>
and the result looks like
`. I tried it on an installation with English and French languages and it returned me `en` and `fr` respectively.
<?php pll_the_languages( array( 'display_names_as' => 'slug' ) );?>
You can find the function reference for the Polylang plugin on this page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, plugin polylang"
} |
Reasons why all thumbnail sizes aren't working
### The situation:
I have both a development environment and a production environment of a website. Both are identical.
### The issue:
On the production site, all post thumbnails show the full image instead of the resized image, even though the resized images are available. On the development site it's working perfectly fine.
The issue occurred after an update on the live site, in which some more images were set to new image sizes.
### What I've checked/tried:
* `add_theme_support('post-thumbnails');` exists and is set in the theme
* Regenerate all thumbnails (using the Regenerate Thumbnails plugin)
* Clear all caches
* File permissions are checked
* The images are being generated, just not shown
* Images are set properly
* Checked for differences in code between the different environments
* Updated / reinstalled WordPress
What could I be missing? | The answer is quite an obscure one. Halfway through I had to change the type of uploading from organized in month- and year-folders to not organized. This caused the old resized images to stop working.
All images had to be uploaded again before they worked. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, post thumbnails, images"
} |
Storing HTML in wp_options
I'm giving my users the option to store HTML in an option with a `wp_editor()`, using the wp settings api to handle the form. I currently do not apply any data sanatization to it, but realize I probably should (`wp_kses_post($option)` ?). I was also wondering if I should do any escaping.
Any tips for good practices on this matter? | Given that you are dealing with email, I'd run `wp_kses()` with a very limited `$allowed_html` array similar to this sample from the Codex:
array(
'a' => array(
'href' => array(),
'title' => array()
),
'br' => array(),
'em' => array(),
'strong' => array(),
);
HTML rendering is even more squirrelly in email readers than browsers (and there are a lot more readers to worry about) so you want to be very careful what you allow. That is going to mean that you will need to truncate the visual option in your editor too. I am sure there are posts here about doing that.
All in all, I'll consider using a very simple markdown and skipping the complexity of the editor completely. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "settings api, sanitization, options"
} |
Fail to get the total number of posts
I would like to get the total number of posts by the following code:
<?php
$published_posts = wp_count_posts()->publish;
echo 'Total posts: '; $published_posts;
?>
The result is `Total posts:` without followed by a number. | This is basic PHP string concatenation
echo 'Total posts: '; $published_posts;
Should be
echo 'Total posts: ' . $published_posts; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, statistics"
} |
How to translate a WordPress.org plugin?
WordPress.org launched recently a new translation mechanism via <
What steps should I make to translate a plugin at wp.org plugin repository correctly?
Can I remove the .po/.mo/.pot files from the plugins folder?
Are the .po/.mo translations already included into the plugin's translations on < website?
Is it possible to translate theme via this approach? | So to make plugin translatable via translate.wordpress.org you need to add text domain into main plugin's file:
/*
* Plugin Name: My Plugin
* Author: Plugin Author
* Text Domain: my-plugin
*/
So to make theme translatable via translate.wordpress.org you need to add text domain into main theme's file:
/*
* Theme Name: My Theme
* Author: Theme Author
* Text Domain: my-theme
*/
And also all the strings should be wrapped with gettext _() functions with the same text domain.
All further details can be found in the official docs below:
* translate.wordpress.org
* how-to-internationalize-your-plugin
* theme internationalization | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "translation"
} |
How to get posts from many categories using WP_Query
I'm trying to get posts from multiple specific categories.
This is my code:
$myquery= new WP_Query( array(
'posts_per_page'=>7,
'cat' => array(5,3,7),
) );
It isn't working - what am I doing wrong? | Below is the code for getting posts from multiple categories using `WP_Query`
Just correct the cat value, it is used without an array. Check out Codex: WP_Query - Category Parameters link for more information.
WP_Query( array(
'posts_per_page' => 7,
'cat' => '5,3,7',
) ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, query"
} |
How to change the title attribute for the WP logo image on wp-login.php
This is how I change the url for the WP logo on the `wp-login.php` page:
function my_login_url() {
$url = esc_url( home_url() );
return ( $url );
}
add_filter('login_headerurl', 'my_login_url');
But the title for the a tag remains the same.
How to change the a tag too?
I mean right now I have this:
<a href=" title="We are using WordPress" tabindex="-1">DEMO</a>
And I want:
<a href=" title="My custom text" tabindex="-1">DEMO</a> | function my_login_logo_url() {
return home_url();
}
add_filter( 'login_headerurl', 'my_login_logo_url' );
function my_login_logo_url_title() {
return 'Your Site Name and Info';
}
add_filter( 'login_headertitle', 'my_login_logo_url_title' );
For details follow link | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin, urls, wp login form"
} |
WP Loop. If featured image is a panorama (3:1 ratio) execute some code
I'm wondering if there is a way to write a condition (if/else) for a featured image. If user submits a featured image in 3:1 ratio (panorama, one edge is 3 times longer than the other edge) - execute some code like this:
if( featured_img_is_panorama() ) { echo "featured img is panorama" }
All this in the loop of course. I added support for featured image (aka `post_thumbnails`) in the `functions.php`. Any help/clue pointing in the right direction much appreciated. Thanks! | This is untested, but should be a step in the right direction:
### within the loop:
//get url of featured image
$atts = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()));
if ($atts) { //if an image was found
$width = $atts[1];
$height = $atts[2];
if ($width / $height > 3) {
echo "is at least 3 times wider than it is tall";
}
}
* WP: get_post_thumbnail_id() »
* WP: wp_get_attachment_image_src() »
(old links, used in original answer)
* PHP: getimagesize() »
* WP: wp_get_attachment_url() »
Thanks to Pat J for the tip about wp_get_attachment_image_src(). Much, much better. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "loop, post thumbnails"
} |
Remove apple-touch-icon link generated by WordPress
I am adding Favicons and Icons to my site manually in a more proper way than what WordPress adds by default. My WordPress is generating the below 4 lines of code automatically.
<link rel="icon" href=" sizes="32x32">
<link rel="icon" href=" sizes="192x192">
<link rel="apple-touch-icon-precomposed" href="
<meta name="msapplication-TileImage" content="
I tried a lot but could not figure out how to stop WordPress from generating this.
Kindly help
Update: After using the function provided by @Gareth, I am getting the following error:
Warning: array_filter() expects parameter 1 to be array, null given in C:\xampp\htdocs\example\wp-includes\general-template.php on line 2466
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\example\wp-includes\general-template.php on line 2468 | Finally I found the answer outside of this place, hence I am posting it here as it may be useful to someone like me.
Simply add this to your functions.php file
remove_action ('wp_head', 'wp_site_icon', 99); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "icon, favicon"
} |
How does the loop know which post to view?
I think I have understood most of how to create my own themes but this one thing: How can a loop in say page.php know which page to view when it loops through all the pages on my site? If I load one of my single pages (ex. contact form) how does page.php knows that it should only load that one specific page when it loops through all of them? | Your loop on `page.php` doesn't loop through all the pages on the site. It loops though all the pages returned by the main query and stored in the `$wp_query` global variable, which is how all of the primary WordPress "pages" work including the post archive pages, category, tag pages, etc. For any one "page" only one page will be in the `$wp_query` global so you only see one.
While the details can get complicated, what happens with a page load in WordPress is that the `WP_Query` class gets instantiated fairly early and it parses the url being loaded and works out what posts to query. That information is shoved into the `wp_query` global variable and is accessed by numerous bits of code thereafter (which is why you don't really ever want to alter that variable manually or via `query_posts()`). It is a wildly complicated mechanism which you can see here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, loop, pages"
} |
MySQL: How to change url in posts from xxx.com to yyy.org?
Recently I switched my domain, unfortunately before that a lot of posts had internal linking to my own other posts by including the old yyy.com domain.
I need to change it in all my posts, via MySQL all "yyy.com" to "xxx.org". What's the command for it? | Instead of replace url directly in mysql db Try with Velvet Blues Update URLs wordpress plugin. It is safe to use this plugin.
Because mysql db has some serialize values for post meta key. In that case your solution will not work proper.
I had used velvet blue update urls plugin many times while migrating wordpress site from one domain to another.
Link For Velvet Blues Update URLs | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "mysql"
} |
How do I set the front page programmatically?
I need to allow my users to set the default page of the blog. So when someone visits, "www.example.com/blog/" the page they see is either the blog posts list or a specific page.
It looks like I can tell which page is already set using:
get_option( 'page_on_front' ): returns the ID of the static page assigned to the front page.
source
Can I change that by using:
set_option( 'page_on_front', 10 );
How would I remove a specific front page that has already been set? Do I set it to null?
**UPDATE:**
I found this call to check if showing blog posts:
get_option( 'show_on_front' ) == 'posts';
source
BTW This is on a network site (Wordpress MU). | If you manually enter the admin URL `wp-admin/options.php` you'll see a list of all options and their values.
`show_on_front` is `page` when a page is selected to show on front. `page_on_front` and `page_for_posts` are `0` when no pages are chosen.
You can use `update_option` to change these values, there is no `set_option` function. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "frontpage"
} |
How do I password protect a page of posts on Wordpress?
I have several pages on my site, and I want to password protect a page which displays the latest posts. Simply going to the admin panel and setting "Visibility: Password protected" isn't doing anything so... Any help?
I am using Wordpress 4.3.1 on a local machine, if that's any use.
Thanks in advance! | When you create a page and assign it to "Page for post" in Settings->Reading, it is not considered a page anymore but an archive. Taht is why standard password protection doesn't work. You will need to build the latest posts page at your own, for example using a page template and/or `pre_get_posts` action. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "password"
} |
I want to show contact form 7 on lightbox
I want to show contact form 7 on lightbox. The theme which ive been using is salient old version. and its not having an custom lightbox feature to show forms on lightbox. | Hi you can perform this with Below code
[formlightbox title="Send me a message" text="Contact me"]
[contact-form-7 id="401" title="Contact form 1"]
[/formlightbox]
For this you needs 2 plugins (1) Contact Form 7 (2) Form Lightbox
you can check this at < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugin contact form 7"
} |
Request object for validate_callback
I'm trying to define a new REST Api endpoint based on WP REST API (version 2) and have question relating to what arguments are available to the `validate_callback` and `sanitize_callback`. Is the `Request` object made available for these callbacks?
For example:
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
'args' => array(
'id' => array(
'validate_callback' => 'my_validation'
),
),
) );
} );
function my_validation (WP_REST_Request $request) {
return is_numeric( $request['id'] ); // Is this acceptable???
} | A quick search through the WP-API source revealed where `validate_callback` is being used:
**wp-api/lib/infrastructure/class-wp-rest-request.php**
$valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key );
In this case, `$this` is an instance of `WP_Rest_Request` \- so there's one. Now, for `sanitize_callback`:
$this->params[ $type ][ $key ] = call_user_func( $attributes['args'][ $key ]['sanitize_callback'], $value, $this, $key );
Same file, there's the `$this` you're looking for. So yes, both should get an instance of `WP_Rest_Request` as their second argument. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugin json api, rest api, endpoints"
} |
What is the best php version to use with WordPress?
What is the best php version to use with WordPress... without going over the top. | There isn't (and shouldn't) be an answer with any _specific_ version for this. New versions come out, old versions get discontinued.
* At the _minimum_ you should use _supported_ version of PHP. This ensures it still receives bug fixes and (or for less recent version) security updates.
* _Preferably_ you should be use the _latest stable_ version of PHP. This ensures you get best possible performance.
PHP site has handy Supported Versions page, which clearly covers currently relevant versions and roadmap for their support. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 8,
"tags": "php, hosting"
} |
Move scripts to footer, but exclude one script?
I used a PHP script to move all scripts to the footer of my site, but some plugins don't work anymore.
I used the following:
// JavaScript to footer --> läd alles im footer!
remove_action( 'wp_head', 'wp_print_scripts' );
remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
remove_action( 'wp_head', 'wp_enqueue_scripts', 1 );
add_action( 'wp_footer', 'wp_print_scripts', 5 );
add_action( 'wp_footer', 'wp_print_head_scripts', 5 );
add_action( 'wp_footer', 'wp_enqueue_scripts', 5 );
Is there a way to exclude a single script from this PHP code? | ### To stop enqueueing a script
We're dequeueing the scripts completely (regardless from header or footer) with a higher priority (10+):
function dequeue_my_scripts() {
wp_dequeue_script('script-handle-here');
}
add_action( 'wp_print_scripts', 'dequeue_my_scripts', 11 );
### To put the script to footer
function enqueue_scripts_to_footer() {
wp_enqueue_script('script-handle-here');
}
add_action( 'wp_footer', 'enqueue_scripts_to_footer' );
### Right way doing this
But the right way enqueueing the scripts in footer is setting the last parameter, of `wp_enqueue_script()` or `wp_register_script()`, to `true`:
function my_custom_scripts() {
wp_enqueue_script( 'script-name', get_template_directory_uri() .'/js/example.js', array(), '1.0.0', true ); //last parameter to true
}
add_action( 'wp_enqueue_scripts', 'my_custom_scripts' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp enqueue script"
} |
Jetpack "Connect to Wordpress" serving insecure content under HTTPS
I set up my site to use SSL and was auditing for insecure content and by process of elimination I found that the plugin serving insecure content is infact Jetpack, and only when connected to Wordpress (it doesn't function without that so that's not much help).
I don't see any options in Jetpack relating directly to either fonts or SSL so I'm not really sure what to look at to get this fixed. I went through the Network tab in Chrome's dev tools and every single resource there is HTTPS.
Jetpack and Wordpress are both up to date (Jetpack 3.7.2 and Wordpress 4.3.1 as of this moment). For now I've disabled Jetpack but I really want it _and_ HTTPS. | Well, this was about half my fault half Jetpacks'. Wordpress in general defaults to non protocol-relative URLs (eg ` not `//`) and the problem was an explicit ` image I used Jetpack to insert into my sidebar. Moving that to a protocol-relative `//` cleared up the mixed content problem.
In general keep an eye out for those kinds of non-relative URLs, I had to redo almost every image URL I had used on the site to get rid of mixed content since Wordpress defaults to leaving those in there. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "ssl, plugin jetpack, https"
} |
Hide a specific post from a page template
I am trying to hide a specific post from a page template? Does anyone have experience with this, would prefer to not have to use a plugin. Was thinking of using wp_post ID but am unsure of how to go about it. | I think that the using **'post__not_in' => array(ID),** is more along the lines I was thinking of:
$args=array(
'cat' => 12, // Make the free-slots cat id
'post__not_in' => array(111)
'showposts' => $show_posts_number,
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, templates, page template"
} |
Write WP Query that selects posts that are part of the same two categories
How would I go about writing an intersect query (using WP Query) that returns a set of posts that are in both category A and category B? | There is a simple way using a default argument...
/*
* You need to get the IDs for the Categories you wish to include
*/
$args = array(
'category__and' => array( 1, 3 )
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() )
{
// Do something to display your posts
...
} else
{
// no posts
}
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, query"
} |
wp_cache_set() or wp_cache_add()
That's the question!
There's not much explanation on `wp_cache_set()` an even less for `wp_cache_add()`.
What should I use in which circumstances? | According with WP Object API documentation both functions accepts these arguments:
* `$key`: the key to indicate the value.
* `$data`: the value you want to store.
* `$group`: (optional) this is a way of grouping data within the cache. Allows you to use the same key across different groups.
* `$expire`: (optional) this defines how many seconds to keep the cache for. Only applicable to some functions. Defaults to 0 (as long as possible).
The difference is:
* `wp_cache_add()`: if the cache key doesn't exist, it add the cache data. If the cache key already exists, the function returns false and does nothing with the cached data.
* `wp_cache_set()`: same as above but if the cache key already exists, the cache data is overwritten. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "cache"
} |
Conditional Tags for specific category of custom posts
How would I show a sidebar only if the post (a custom post type) belongs to a specific category of that custom post type?
I was looking for something like:
if ( is_singular( 'my_custom_post_type' ) && in_category( 'my_custom_post_type_category' ) )
but `in_category` doesn't seem to work. I tried with the category ID too, but no luck.
The theme uses the name `class_category` as the main category for this custom post type. | Try using `has_term()` which accepts a `term_name`, `term_id`, or `slug` to test again. You'll need to pass the `post_id` too, something like this:
global $post;
if( isset( $post ) && is_singular( 'my_custom_post_type' ) && has_term( 'my_custom_post_type_category', 'my_custom_taxonomy', $post->ID ) ) {
// Code Goes Here...
}
You _may_ also be able to use `has_category()` which work very similar but if I were a betting man I'd bet that that function would only work for the built-in Post Categories but still worth mentioning. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, conditional tags"
} |
How to change default text for specific post type
**Prelude:**
Let's say the text **"Comments are closed"** is a default WP String and you wanna change that text string to something else like **"Hello World!"** if `is_singular('post-type')` is true.
**Issue:**
Now, I do know that there is a plugin called Say What? which does this exact thing, you just have to provide the string of text and the respective text domain. But the problem is that whatever you change in this plugin it will become global for the entire website. You cannot use and conditional check and then change the text if the condition is true.
So, can any of you let me know if I can change the text without this plugin via normal code so that I can use any conditional statement I want.
Any help will be appreciated. Thanks. | Yes you can do it, just find the file where the text resides, maybe single.php or single-{post_type}.php or archive-{post_type}.php Then, look for the string you want to change erase it and set a variable, something like this:
If the file where the string is, is a template file for that specific post type, the you will only replace the string for whatever you want:
<h2>Comments are closed<h2> //Replace comments are closed for Hello World
Remember the strings you find in comments, footer or sidebar are in separate files, and, in that case, and in the case the file that is giving the HTML structure to the post type is single.php, you'll have to do something like this inside the loop:
<?php
$post_type = get_post_type( get_the_ID() );
$the_string = "comments are closed";
if ($post_type === "my_post_type") {
$the_string = "Hello World!";
}
?>
<h2><?php echo $the_string; ?></h2> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, actions, text, textdomain"
} |
create web service for android app using wordpress website
I have to create Web services for android app using WordPress Database. where user can login and register using android app. that record will be saved in WordPress database. display All the posts of wordpress site in android app using wordpress database table. user can Create and Update User Profile ,Login , Register ,Posts etc.
I want to Know any WordPress API or web services Plugin is there which can interact with WordPress Tables. Any help would be appreciated. | The Wordpress JSON API plugin may be of use to you, which lets you access the Wordpress tables via a RESTful API. You can also add your own custom controllers. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, api, web services"
} |
Why do I sometimes get an attachment id string instead of a url from an image's guid field in the post table?
If I do a query of the post table for post type 'attachment' sometimes the guid field will contain an attachment id, "< instead of a URL. How can I convert a string like this into the attachment url? | I found that part of the actual path, relative to the uploads folder, is stored in the postmeta table for the meta_key of '_wp_attached_file' which can be obtained, as Milo suggested, by using wp_get_attachment_url. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "media library"
} |
if wp_query taxonomy term have posts
Having formulated my $query for a custom taxonomy on a page template, how would I ask if a specific term has posts?
$args = array(
'post_type' => 'exhibitions',
'tax_query' => array(
array(
'taxonomy' => 'exhibition',
'field' => 'slug'
),
)
);
$query = new WP_Query($args);
Assuming I'm on the right track, a verbal description of the sort of conditional statements I'm looking for would be:
if the $query taxonomy term 'current' have posts, do something;
elseif the $query taxonomy term 'upcoming' have posts, do something else; | I'm not sure what you exactly need, but normally, by default, `get_terms` returns only terms that actually have posts assigned to them
$terms = get_terms( 'exhibition' );
var_dump( $terms );
Apart from this, I really do not know what you exactly need | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp query, tax query"
} |
How to share posts (and plugins) between existing site and new, separate dev/test installation?
* A client has an existing WP installation.
* I want to setup a dev/preview site that pulls same page/post content as existing site (and has same active plugins and settings), and I don't want the existing site to be affected.
How can I do this? Is is safe to do a separate WP install in a new directory and just feed it the same DB credentials (including WP table prefix) during the install process? | There are tools available for simplifying the synchronization of databases between multiple WP installations, such as WP Sync DB.
As @jdm2112 mentioned, using a copy of the database—versus attempting to use the same database—reduces the risk of development work interfering with the production environment. However, simply making a copy of one site's WP database is generally insufficient for using it on another site. You can read more about moving WordPress here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, customization, previews"
} |
Prevent author from editing comments from others in their post
I want to prevent other authors from editing other people's comment made in their post.
Does anyone here know how to do this? | Try use the following code in your themes functions.php
//
function restrict_comment_editing( $caps, $cap, $user_id, $args ) {
if ( 'edit_comment' == $cap ) {
$comment = get_comment( $args[0] );
if ( $comment->user_id != $user_id )
$caps[] = 'moderate_comments';
}
return $caps;
}
add_filter( 'map_meta_cap', 'restrict_comment_editing', 10, 4 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments, author"
} |
Include Information Text within Registration Page
I'm running WordPress with BuddyPress. So I noticed a lot of AdBlocker are causing bugs on my site like to remove the Google reCAPTCHA and people aren't able to register to the page without notice. To inform the user that this not a bug of my Website I would like to include some simple text to the registration page (and hopefully without any plugin and core digging).
Does anyone know a way to do this? As example via theme functions? | Please see this thread: <
This possible by creating a javascript file in your theme folder, enqueue it properly and than execute some message (maybe in jQuery model, or alert box in JavaScript) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "html, buddypress"
} |
Cannot login in Wordpress even after changing hash password in phpmyadmin
An hour ago I changed the password of my Head Admin user. But after this I was not able to login anymore. So I have tried to reset the password in PHPmyadmin with the md5 encoding and even with this Wordpress hasher < but it does not work anymore.
I also tried other accounts, but they cannot login as well. The last thing I have tried is to use the new password function in the wordpress login screen, and also this does not work.
Does anyone have an idea what I need to do? Is the emergency reset script of Wordpress an option? < | Finally I used the `wp_set_password();` function as the emergency reset script documentation of Wordpress explains, which helped me to set a new password for my admin account. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp admin, users, login, woocommerce offtopic, password"
} |
How do I intercept and modify the functionality of wp_get_attachment_image()?
I have a site I'm building in wordpress that has ~80GB of high resolution images, and it's exceeding my managed host's storage space. My plan is to move all the images to S3, but I noticed that `wp_get_attachment_image()` automatically prefixes the src with `/wp-content/uploads` instead of respecting the path stored in the database.
Is there a way to hook into that method and modify it to not include the prefix? | It might be a solution to string replace /wp-content/uploads with '' (empty) like for an example:
Lets say: wp_get_attachment_image() returns = '/wp-content/uploads/myimage.png';
<?php
echo str_replace('/wp-content/uploads/', '', wp_get_attachment_image());
?>
This will result in echo: 'myimage.png'
Try this:
function alter_image_src($attr) {
$attr['src'] = str_replace('/wp-content/uploads/', '', $attr['src']);
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'alter_image_src');
In your functions page (of theme). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "attachments, images"
} |
Show certain number of post from tags
Hi i am using the query below to display post from a certain tag term, but what I want it to show multiple post.
So far the query is displaying only 1
<?php
$args = array('tag_slug__and' => array('morning-meat'), 'showposts' => array ('3'),);
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
<ul>
<li><?php the_title(); ?></li>
</ul>
<?php endforeach; ?>
I can't figure out the problem. | I believe `showposts` as been depreciated in favor of `posts_per_page`
$args = array(
'posts_per_page' => 3,
'tag_slug__and' => array('morning-meat')
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query, tags, array"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.