INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How do I insert an amazon search widget into posts or pages?
How do I insert an Amazon Search Widget into posts or pages? The source code is:
<SCRIPT charset="utf-8" type="text/javascript" src=" </SCRIPT> <NOSCRIPT><A rel="nofollow" HREF=" Widgets</A></NOSCRIPT>
* * *
**EDIT:**
The reason why the widget doesn't appear after embeded the above code into HTML is that the widget is blocked by **AdBlock**. | You're best bet is to put the amazon javascript script code into a widget, and then add the widget into a post/page using a shortcode. Give a look at this plugin.
<
(I've never used it, but the concept seems correct.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, scripts"
} |
Why does my content disapear when I make a page to match an archive name?
I made a custom post type called 'education'. I have added several pages to it. When it was first created I could go to < and see the posts, but I wanted to edit the layout. So I created a page called 'education' with the same permalink. Now it does not display any content.
Why does WordPress do this? How can I edit the layout if I can't create a page to attach a template? | The WordPress template hierarchy is your friend. <
This provides a very detailed flow for how WP determines which template to load.
If you are ever uncertain about which template is loading, this little function is handy. Paste in your theme's functions.php and it will display the template used at the bottom of the page.
add_action('wp_footer', 'wpse_show_template');
function wpse_show_template() {
global $template;
print_r($template);
}
That being said, creating a page with the same slug (education) as your post type archive will produce unexpected results, as you've seen.
The proper way to add your static content to the Education archive is via the archive-education.php template. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, pages, page template"
} |
How can I allow user to select minimum privilege smartly
We can easily asses a user's role using `current_user_can()`, but it doesn't support an array of user roles but a single role. So we have to check each of the role multiple times:
if( current_user_can('administrator') || current_user_can('editor') ) {
//do this
}
I'm making a WordPress Plugin, I need the administrator should choose the minimum privilege to administer the plugin. If the roles are hierarchical then they are like so (for single site):
* Administrator
* Editor
* Author
* Contributor
* Subscriber
If the admin choose author, then I have to do 3 OR checks as shown above ( _if x || y || z_ ).
Is there any smart way I can choose for this purpose so that I can let them choose the minimum privilege but I can handle it smartly too.
Thank you. | You are using the right WP function but unfortunately not passing the right parameter to make this work for you.
`current_user_can()` accepts capabilities as well as roles as parameters.
In the above you are using roles and not capabilities.
You can use capabilities to make it work.
For example, if you want the minimum privilege role is author your code would look like
if ( current_user_can( 'edit_published_posts' ) ) {
//do this
}
This will allow all the roles including author to have the privilege and would stop users with roles contributor and subscriber from the access.
You can read the details of roles and capabilities from the codex here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "user roles"
} |
Menu Details Output in Javascript
I have to output page, parameters( Page Url, Page Name, and Page's featured image) in javascript loop, one by one
I think we can display it through NavMenuItems or NavMenu functions
Pages displayed will be those a user is allowed to see e by user hierarchy,
Any suggestions on how to proceed...?? | You can just use `wp_get_nav_menu_items( $menu, $args );` to get list of menu items created in appearance.
You can print result the way you want. Before printing just make sure the datas are not empty and so. I didn't add any validation. So use according to your need.
For example:
We'll try to print the data at `wp_head`
add_action('wp_head','menu_to_js');
function menu_to_js(){
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );//$menu_name should be your menu name
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_items = json_encode($menu_items);
//So now we have json encoded $menu_items, put that in javascript
?>
<script>
var menu_itemss = "<?php echo $menu_items; ?>";
//now manipulate in js and use the way you want.
</script>
<?php
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, javascript, navigation, plugin wp pagenavi"
} |
Cross reference custom post types
Just curious if can I autopopulate custom post fields (like checkboxes or select items) based on another custom posts setup?
My goal is to create a custom post types "employees" which can have assigned multiple service areas (stored as another custom post types), as group of checkboxes or drop downs fileds, as well will be able to assigned multiple office locations (stored as another custom post types) as well as group of checkboxes or drop downs fields to each employee. Main goal is to avoid redundancy and pull office locations and services from one centralized location as options fields for employees custom post type.
Or maybe there is a better solution to tackle that problem like using categories of employees custom posts for service areas and tags (for custom post types) as office locations?
Thanks | I have fund that Types plugins can handle that kind of functionality out of the box. More here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, categories, custom field, tags"
} |
set_post_thumbnail() shows Unattached on backend under Media
I'm using front-end form to submit content and use
// Set thumbnail
$newupload = set_post_thumbnail( $post_id, $att_id );
echo $newupload;
to set the Featured image on the post. It actually works fine but it does not show up in the backend under Media page.
 works, so will look for an alternative resolution to the category base issue. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "categories, permalinks, htaccess"
} |
Menu / div of year and months of blog posts?
I want a menu or a dive with this content where you can click on and see the blog posts from the selected date
that is like this
BLOG
-2014
-january
-february
-march
-....
-2013
the months and years should be added automatically.
Is there something that can do it? | The `wp_get_archives` function will generate a list of links to date archives. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, blog"
} |
Error in WP_update_post
i make php file outside from wordpress folder to edit wordpress post and i get error when i use this code.
wp_update_post
<?php include '/go1/wp-includes/post.php';?>
<?php
// Update post 1 hello word
$my_post = array(
'ID' => 1,
'post_title' => 'This is the updated post title.',
'post_content' => 'This is the updated content.',
);
// Update the post into the database
wp_update_post( $my_post );
?>
my error is:
> Notice: Use of undefined constant ARRAY_A - assumed 'ARRAY_A' in D:\AAApc\training\XAMPP\htdocs\go1\wp-includes\post.php on line 3628
>
> Fatal error: Call to undefined function wp_cache_get() in D:\AAApc\training\XAMPP\htdocs\go1\wp-includes\post.php on line 664 | The key to using WordPress outside of WordPress is include the _wp-load.php_ file:
So your code will like:
<?php
// Include the wp-load'
include('YOUR_WP_PATH/wp-load.php');
// Update post 1 hello word
$my_post = array(
'ID' => 1,
'post_title' => 'This is the updated post title.',
'post_content' => 'This is the updated content.',
);
// Update the post into the database
wp_update_post( $my_post );
?>
It's should work...
Once the _wp-load.php_ file is included, the entire wealth of WordPress functions is provided to you. While the sample code above gets recent posts, you can do your own custom queries with WP_Query or get_posts(). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, array, wp update post"
} |
Transfer WordPress post to RoR site: is the REST Api the only and/or best solution?
I'm creating a new version of my site without WordPress, using Ruby on Rails. How can I transfer all my posts and users to this new site ? I was thinking of using the REST Api but none of the functions related to the Posts allow to retrieve the whole post (images+text+author): <
What would be the best solution ? It should be possible even if my new site is powered by Rails since the pages are always just HTML/CSS/JS and does not include PHP. | Use the file that wordpress generate at "export". It should contain the basic info you are talking about (although not the user's passwords if you are expecting to get it as well). It is just an xml file which you can parse, you can even look at the code of the wordpress importer for guidance. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, rest api"
} |
How can I use wordpress functionality outside of WP framework
I require to retrieve a list of the recently created blog posts or any Query-based usage of WP posts inside my PHP website and not within WP framework.
I am new to Wordpress and stucked here. I already tried with include `wp-includes/post.php` file but i guess its still not working. Facing error regarding `undefined constant` and `function`. I don't know whether I am correct or not here. Is there any way to resolve this? | It's just simple, same reply from Error in WP_update_post but in your case there is small change.
Just use `wp-load.php` as include. No need to include `post.php`. Once the `wp-load.php` file is included, the entire wealth of WordPress functions is provided to you.
For pull the recent post, you need to use `wp_get_recent_posts()` wordpress function which is from WP framework.
So your PHP code will like:
<?php
// Include the wp-load'
include('YOUR_WP_PATH/wp-load.php');
// For example get the last 10 posts
// Returns posts as arrays instead of get_posts' objects
$recent_posts = wp_get_recent_posts(array(
'numberposts' => 10
));
?>
Let me know if there is any doubt/query from this. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "errors, get posts"
} |
Remove a field from json in wp rest api v1
I want to create an android app for a WordPress blog using WordPress rest api.
For optimization I want to remove content field and some other fields when I get all post to show them in my main list and when user click on a link fetch the content filed from the post link.
Is there any way to remove them? | I think you could use WP-REST-API-Filter-Items plugin. With the plugin you can define a list of fields you want and you do not have to fiddle with WordPress or PHP | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "json, wp api"
} |
Production Site: Moving from WordPress RC to Final Release Version
Although it's not recommended, I'm planning to use the 4.4RC for a new production site (the new Twentysixteen theme is perfect for what I need). Once the final release version is out, what is the process for updating? Is it a simple core update? Do I need to do something different? If so, what?
Would it be better to use the Beta Test plugin?
The only relevant question had no answer.
Switch from Beta Version to Stable Version | I would definitely recommend checking out the beta-tester plugin: <
. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wordpress version"
} |
Editor / Add Media: Is it possible to only allow galleries?
I am writing a theme for a client where the employees sometimes have trouble using Wordpress correctly. I am using custom fields to let them add a gallery to a portfolio item (which is just a custom post type). Sometimes they just add images instead of a gallery, which is possible since the field in the portfolio is just a WYSIWYG Editor field with ACF. That is a problem because the layout is not working then.
The client now asked if it was possible to only allow them to add galleries. And not single images.
Is there a way to do that? Has anyone ever seen something like that? I know, it is ridiculous, but maybe there is a way... | I'm used to deal with ACF configurations and I think that the solution to your problem is quite simple, and is integrated in the ACF "gallery" field configuration options.
Check out this link, where you will find described all the options for a "gallery" field. As you will see, there's a parameter **"minimum selection"** which description is:
> The minimum number of images that are required for the field to validate. Defaults to 0
As simple as writing '2' in the configuration panel for this specific field, and ACF will check before saving if there are two or more images. If not, an alert message will appear.
I hope it helps! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom field, gallery, editor"
} |
Assign a category to all articles
I have a database of 4000 articles and I need to assign a specific category to all of this articles.
How I can do? If I try by selecting all in the CP and trying to modify them, i get an URI too large error from my webserver.
I also need to assign a single specific author to all 4000 articles. | If you can access the database directly, you could
1. Check for the ID of the category you want to assign
2. Check for the Author ID
Then run the following MySql (on your own risk):
INSERT INTO `#__term_relationships` ( object_id, term_taxonomy_id )
SELECT ID, 1 FROM `#__posts` WHERE `post_type` = 'post' // where 1 is your desired category ID
UPDATE `#__posts` SET `post_author` = 2 // desired author ID | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, author"
} |
WP_Query count of different meta key values
I need to get count of different values of meta_key:
Let's say I've got meta_key `$class` & there's only three different values: `1`, `2` & `3`.
//My WP_Query
$ads = new WP_Query(array(
'post_type' => 'ads',
'meta_key' => 'ads_class',
'orderby' => 'meta_value_num'
));
if ( $ads->have_posts() ) :
//Do stuff
//Now I need to know how many have ads_class of "1", "2" and "3" - all as different vars | Just loop over the posts and bump the count based on the value of `ads_class`:
$ads_1 =
$ads_2 =
$ads_3 = 0;
while ( $ads->have_post() ) {
$ads->the_post();
switch ( ( int ) get_post()->ads_class ) {
case 1 :
$ads_1++;
break;
case 2 :
$ads_2++;
break;
case 3 :
$ads_3++;
break;
}
}
$ads_1; // Number of "1" ads
$ads_2; // Number of "2" ads
$ads_3; // Number of "3" ads | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, wp query, count"
} |
Limiting woocommerce line_total decimal length
I am trying to get line_total woocommerce price, but i just cant figure out how to deal with number of decimals. It is now showing price with 4 decimals like 5.5444$ and i want it to show max 2 decimals, like 5.54$.
Does anyone know what am i doing wrong? I have no problems with orger_total price which is showing correctly with just 2 decimals.
$myID = 2859;
$myorder = new WC_Order($myID);
foreach ($myorder->get_items('line_item') as $item) {
$Data = $Data.OrderLine($item["name"], $item["line_total"], $item["line_tax"], $item["qty"], "piece", "x");
}
Is there a way to limit `$item["line_total"]`to max 2 decimal numbers? | Just round the decimal to two digit as per your requirement.
$myID = 2859;
$myorder = new WC_Order($myID);
foreach ($myorder->get_items('line_item') as $item) {
$rounded_total = round($item["line_total"],2);// allow 2 decimal and avoid further
$Data = $Data.OrderLine($item["name"], $rounded_total, $item["line_tax"], $item["qty"], "piece", "x");
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, functions, woocommerce offtopic, order"
} |
How do I hide certain taxonomy boxes from users in admin add post page?
I would like to hide this particular taxonomy box in the admin on the add new post page.
{
remove_meta_box( 'resourcetypesdiv', 'resource','side' );
}
add_action( 'admin_menu', __NAMESPACE__ . '\\remove_meta_boxes'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, admin"
} |
Hide menu from homepage
I am using the WP- Spirit 01 theme and would like to know how can I hide the navigation menu ONLY from the website homepage. I don't have my website live yet. The css code bellow works to hide the menu everywhere not the homepage.
.drop-down ul{
display:none;
}
Will be very thankful and happy if someone helps me as soon as possible! | You should be able to short circuit the menu by conditionally `return`ing an empty string by adding this code to your theme `functions.php` :
add_filter( 'pre_wp_nav_menu', 'wpse_210095');
function wpse_210095($menu) {
if (is_home()) {
$menu = '';
}
return $menu;
}
You can see in the Core where this logic executes:
260 $nav_menu = apply_filters( 'pre_wp_nav_menu', null, $args );
261
262 if ( null !== $nav_menu ) {
263 if ( $args->echo ) {
264 echo $nav_menu;
265 return;
266 }
267
268 return $nav_menu;
269 } | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "menus, navigation"
} |
get_month_link uses what wordpress template?
I tried using
`archive.php` and `category.php`
but always `index.php` is used of my template. How can I customize what template file is used? | `get_month_link()` doesn't use any template. It just creates a link to date based archives. The actual template used is decided by a rather complicated template hierarchy system managed by Core. Essentially there is a cascading sequence of files that will be used if those files are provided by the theme:
1. `date.php`
2. `archive.php`
3. `index.php` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "templates, api, template hierarchy, codex"
} |
Custom query: Get all posts that are from a certain category?
This is what I have:
global $wpdb, $month;
$months = $wpdb->get_results( "SELECT *
FROM $wpdb->posts
WHERE post_type = 'post' AND post_status = 'publish'
AND DATE_FORMAT( post_date_gmt, '%Y' ) = $y
GROUP BY DATE_FORMAT( post_date_gmt, '%Y-%m' )
ORDER BY post_date_gmt DESC
");
The problem is, this returns all posts from that time, but I want only posts that are in category 11.
Is there an easy way to achieve this? | it's quite easy:
$months = $wpdb->get_col("SELECT DATE_FORMAT(post_date_gmt, '%m')
FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships as t
ON ID = t.object_id
WHERE post_type = 'post' AND post_status = 'publish' AND t.term_taxonomy_id = 11
AND DATE_FORMAT(post_date_gmt, '%Y') = $y
GROUP BY DATE_FORMAT(post_date_gmt, '%Y-%m')
ORDER BY post_date_gmt DESC");
term_taxonomy_id is the category. And I join on the object ID | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp query, wpdb"
} |
How to change menu hover color to white on my theme?
When you look at my themes menu, you can see when you hover over the menu links, the hover color is red. That is good. What you can also see is that the link inside the red hover turns from white to black. I would like to keep it white and do not know how to approach it.
< | Go in your style.css line 18 and delete the "color" attribute for `#navigation .sf-menu > li.sfHover > a` and the one for `#navigation .sf-menu > li > a:hover`. Alternatively, you can set it for `color: white` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css"
} |
How can I edit comment notification email content?
I have to edit the mail content which is default one to send notification to the post author when a comment is submitted. I need to add my custom content by replacing the existing comment mail content. So is there any action or function to override this default email template with mine custom one. | You can apply a filter to `comment_notification_text`:
1525 /**
1526 * Filter the comment notification email text.
1527 *
1528 * @since 1.5.2
1529 *
1530 * @param string $notify_message The comment notification email text.
1531 * @param int $comment_id Comment ID.
1532 */
1533 $notify_message = apply_filters( 'comment_notification_text', $notify_message, $comment->comment_ID );
If you have extensive changes to make, since the function containing that hook is pluggable, you may find it easier to replace the entire function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
How to add Request header in WordPress remote api calls
Hey am new to WP development, can any one tell me how to add request headers in wp_remote_get() or wp_remote_post() remote api calls.
I tried the following but didnt work
$response = wp_remote_get( add_query_arg( array(
'Affiliate-Id' => XXXXX,
'Affiliate-Token' => XXXXX
), $api_url ) , array( 'timeout' => 10)); | If you want to send `Affiliate-Id` and `Affiliate-Token` in headers then you need to pass them in the optional arguments of `wp_remote_get` function.
Example:
$response = wp_remote_get( $api_url ,
array( 'timeout' => 10,
'headers' => array( 'Affiliate-Id' => XXXXX,
'Affiliate-Token'=> XXXXX )
)); | stackexchange-wordpress | {
"answer_score": 22,
"question_score": 8,
"tags": "plugin development, wp remote get, wp remote post"
} |
Theme Dev | Convert Template to Theme
What is the solution in theme development for section in this template Home Page so user can edit from admin panel.
1. "Main Features" Section, at bottom of slider, it says "Strong Structure", "Global English", "Dynamic Change", "Exponential Growth"
2. "The Boxed Content" Section, has "Goal Oriented" and 3 More... | If you mean you want a widget to control content dynamically from the admin panel, then you can use the Advanced Custom Fields plugin by Elliot Condon to create custom dynamic content and retrieve it every place all over the website. After installing the plugin, simply create fields in the plugin page and get the content in every HTML tag you want. Like this:
<?php the_field( 'Your Custom Field Name' ); ?>
You can see a real example and full documentation on the ACF website. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, templates, customization"
} |
Getting 404 in the Javascript
I have directory called "api" and in that I want to run a php script called "tweet.php". This script file is calling inside a JS file. However I am getting a 404. Need help to solve the issue.
Link to the project directory <
Thanks | I think this is not good idea - create many enter points. Open Web Inspector and check your URL which using in JS code.
But much better use the default `admin_url( 'admin-ajax.php' )` to creates path which should be used in Java Script. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, twitter"
} |
Using single.php from plugin folder instead of default template folder
I am trying to figure out how to use another single.php for a custom plugin I'm making. It's for a custom post type.
Because if people install this plugin, they won't have the custom single-product.php in their theme folder. That's why I want it to be in the plugin folder.
Is there a way to change the path of this custom post type's single.php or a way to automatically generate the file in the theme folder after installing this plugin?
Thanks in advance | I think a hook into `template_include` like described here could be a proper way to do this.
Code could be like this:
add_filter('template_include', 'my_plugin_templates');
function my_plugin_templates( $template ) {
$post_types = array('post');
if (is_singular($post_types)) {
$template = 'path/to/singular/template/in/plugin/folder.php';
}
return $template;
} | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 5,
"tags": "posts, pages, single, customization"
} |
Custom search page wont allow URL params
I am trying to create a custom search page but having issues.
I have a file called "searchpage.php" which is set as the default page for a page created in the WP Admin called 'search'.
I am trying to call the URL: /search?s=test
However, the browser changes this URL to: search/?s=test which 404's.
If I rename my searchpage.php to search.php and just use the URL: ?s=test everything works fine and my search page shows correctly. I would however like the page to have search before the term so thats its more recognisable and relevant to the user.
I achieved this on another project but no matter what I do I cannot get it working on this case. | Create your own Custom Endpoint or Rewrite Rule to capture the s param. Then route it to your search page with a Template applied or hook the Template Redirect. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "search"
} |
Accept HTML in custom function
I have a custom field for a WordPress page to display a subtitle. How do I get the following function to accept HTML code such as elements?
function cms_page_sub_title(){
global $cms_meta, $post;
if(!empty($cms_meta->_cms_page_title_sub_text)){
echo '<div class="page-sub-title">'.esc_attr($cms_meta->_cms_page_title_sub_text).'</div>';
} elseif (!empty($post->ID) && get_post_meta($post->ID, 'post_subtitle', true)){
echo '<div class="page-sub-title">'.esc_attr(get_post_meta($post->ID, 'post_subtitle', true)).'</div>';
}
}
output is
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"><?php cms_page_sub_title(); ?></div>
Thanks | Trying to store markup in the database is generally a bad idea-- some reasons being:
1. Certain characters need to be escaped to be put in the database
2. Having markup in the database will negatively effect any searches you may need to run on the data, now or in the future.
3. Having markup in the database will complicate attempts to reuse the data in different contexts, now or in the future.
Just store the raw data in the database and format it on output. The basic code would look like:
$meta = get_post_meta($post->ID, 'post_subtitle', true);
if (!empty($meta)) {
$mstr = '<span class="some-class"'.$meta.'</span>';
}
You can automate that by creating a shortcode or by inserting it using the `the_content` filter, for example. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, html"
} |
I can't fetch query parameters ($_GET parameters) with get_query_var
I am developing pagination for a list of posts in my plugin. I've added a custom parameter in my `plugin_functions.php` file:
add_query_arg('pworkspage', 1);
As you can see it defaults to "1". Now, whenever I visit the custom admin page of my plugin with that parameter in the URL (`www.example.com/wp-admin/admin.php?page=mycustompage&pworkspage=2`) my script can't see the parameter at all.
I am retrieving the parameter like this:
$page_nr = get_query_var('pworkspage', 1);
The variable `$page_nr` is equal to `string(0) ""`.
I tried a different approach using the `query_vars` filter but I got the same results.
**Am I doing something wrong?** | Query vars are for use in the main `$wp_query` query object, your custom admin page has no main query, so no vars are parsed into a query object that can be accessed via `get_query_var`. I don't think there's anything WordPress-specific that can be used in this case, I would just access the value via `$_GET`. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "php, plugin development, pagination, query variable"
} |
Content not displaying on page
<?php
/* Template Name : Home
*/
?>
get_header(); ?>
<?php get_footer(); ?>
When I type anything on content editor of the page it doesn't show any thing.
How do I make it working? | you need to add the loop before and after and add the function the_content()
something like this:
<?php
/**
** Template Name : Home
**/
get_header(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
<?php get_footer(); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages"
} |
Create metaboxes based on custom post type
I am using Metabox to create metaboxes for Worpdress Post and it works like a charm. Now I have installed MetaBox Custom Post Type Extension for create CPT and it works good to. I have Types plugin installed for same purpose, create CPT so I can work either with Metabox or Types. I have created a CPT with slug `publicity` and I want to add some Metaboxes only to that CPT. How I can achieve this? I know how to create the Metaboxes using the plugin I just don't know how to make a difference between Wordpress post and this custom post type, perhaps by adding some conditional at `functions.php` and checking for post type slug and then including needed files but not sure and I need some push, any advice? | When defining your MetaBox before registering it, just set the PostTypes it is applicable for:
$f711_meta_boxes[] = array(
'id' => 'details',
'title' => __( 'Details', 'f711_theme' ),
'pages' => array( 'publicity' ), // change this values
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => __( 'Fischi ist', 'f711_theme' ),
'desc' => __( 'Jaja, Beschreibung', 'f711_theme' ),
'id' => 'f711_is',
'type' => 'select',
'options' => array( __( 'gut', 'f711_theme' ), __( 'super', 'f711_theme' ))
)
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, plugins, metabox, plugin types"
} |
Where and how to define variables for URLs etc
I have one online version of a site, and one developer version which I am working and making changes on.
If I have a form with a url which the user will be redirected to:
<input type="hidden" name="cancelurl" value="
So when updating the live site, I have to change the url to the one that's valid for the live version.
So it would be more preferrable to use a variable or constant which is defined somewhere.
<input type="hidden" name="cancelurl" value="<?php $cancelurl ?>">
Then I can transfer the code without having to change the urls.
So my question is where and how do I define such variables or constants? | I believe you can just use `site_url()` \+ the path - so for instance:
<input type="hidden" name="cancelurl" value="<?php echo site_url('/cancel/'); ?>"> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "variables, constants"
} |
Group child category IDs based on their parent category
I have IDs for my child categories, `11,14,21,35,38,39`, where these all are various child categories from their main category:
* Parent category `1` has: `11,14`
* Parent category `2` has: `21`
* Parent category `3` has: `35,38,39`
How can I group my child IDs as per their parent category, like below?
array(
1 => array ( 11,14 ),
2 => array ( 21 ),
3 => array ( 35,38,39 )
) | The quick take would be something like this:
$categories = [ ];
$parent_categories = get_categories( [ 'parent' => 0 ] );
foreach ( $parent_categories as $parent_category ) {
$id = $parent_category->term_id;
$categories[ $id ] = wp_list_pluck( get_categories( [ 'parent' => $id ] ), 'term_id' );
}
The important bit is a `parent` argument, which limits retrieved to immediate children (parent of 0 is a top level).
Depending on how _many_ of these you have it might be preferable to instead retrieve all of them first and then re-arrange out of singe result set. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "terms, categories"
} |
Trying to prepend a Hashtag symbol to the_tags links
I want to prepend a hashtag (#) in front of the tags on my post pages in Wordpress using jQuery. This code is not working:
$('div.tags a').prepend('#');
This is the php:
<div class="tags">
<?php the_tags( ' ', ' ', '' ); ?>
</div>
I don't want the "#" to be part of the the stored tag, just added for display purposes. Thank you. | I didn't want to edit the tags themselves, I just wanted to add the "#" for visual purposes.
I decided to add this to the CSS to solve the problem:
.tags a::before {
content: '#';
}
Thanks for your time and input. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, jquery, links, tags"
} |
Add video from youtube in post
I need to add video from youtube in certain place on my page. I added link in post like ` (post contains only this link), and then I added code on my page
<?php
$post_id_63 = get_post( $post_id = 63 );
if($post_id_63) {
$post_id_63_content = $post_id_63->post_content;
echo $post_id_63_content;
}
?>
but I get just text link on my page, not video. What did I do wrong? How to fix it and make it work ? | This is overview how you can make it working:
First with below code you can detect youtube URL for details Please read:
$reg = preg_match('|^\s*(https?://[^\s"]+)\s*$|im', $post_id_63->post_content, $matches);
if (!$reg) return false;
$url = trim($matches[0]); // youtube video url
echo wp_oembed_get($url); // this will return youtube vidoe
For details please read: Wp_oembed_get
we need to use `wp_oembed_get` to make URL into video from post content
Thanks! | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "videos"
} |
Exclude current post when getting related post on custom post type and taxonomy
The below will return the other post in the same category but it will also return the current post too.
Is there a way to exclude the current post from the query?
$args = array(
'post_type' => 'custom_post_type',
'tax_query' => array(
array(
'taxonomy' => 'custom_taxo',
'field' => 'term_id',
'terms' => array(1,2,5),
'operator' => 'IN'
)
)
);
$query = new WP_Query( $args ); | Simply add
'post__not_in' => [get_queried_object_id()],
to your array of query arguments. `get_queried_object_id()` will return the post ID of the currently viewed single post, and `post__not_in` will skip the posts whos ID's was passed as an array to the parameter | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "custom post types, wp query, custom taxonomy"
} |
StoreFront Wordpress theme: How can i create a new Home page with Custom design same as template
I am getting too frustrated while creating new home page using template in Storefront theme. <
With the help of this < i tried bt not getting success.. anyone can tell me how can i do this without plug-in..
I want to change home page , and want to show my custom template home page. –
**Template Script**
<?php
/**
* Template name: Homepage My Custom
*
* @package storefront
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
**My Custom Home Template**
</main><!-- #main -->
</div><!-- #primary -->
<?php get_footer(); ?> | First step in modifying a theme, is creating a child theme.
Now that you have a theme that is basically the same as the original, you can simply copy files of the original theme that you want to modify into exactly the same relative location as in the original theme and modify them to whatever you need. In your specific case, after locating the page template for the home page and copying it you can just modify the code in it and there is no need to create a new one. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, themes"
} |
how to show list image in gallery?
i has create galley in post as: `[gallery columns="6" link="file" ids="156,113,99,67,103,102"]`
Now, how to show list image in `[gallery columns="6" link="file" ids="156,113,99,67,103,102"]` in to index as:
<a href="#" title=""><img src="link image in gallery">
.....
<a href="#" title=""><img src="link image in gallery">
Any idea give me!
Thanks | I guess you should use `get_post_gallery_images` function, this is example from documentation below
function pw_show_gallery_image_urls( $content ) {
global $post;
// Only do this on singular items
if( ! is_singular() )
return $content;
// Make sure the post has a gallery in it
if( ! has_shortcode( $post->post_content, 'gallery' ) )
return $content;
// Retrieve the first gallery in the post
$gallery = get_post_gallery_images( $post );
$image_list = '<ul>';
// Loop through each image in each gallery
foreach( $gallery as $image_url ) {
$image_list .= '<li>' . '<img src="' . $image_url . '">' . '</li>';
}
$image_list .= '</ul>';
// Append our image list to the content of our post
$content .= $image_list;
return $content;
}
add_filter( 'the_content', 'pw_show_gallery_image_urls' );
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "gallery"
} |
How to read out the excerpt length (for if-condition)
I'm trying to do is the following. **If the excerpt length is shorter than 30 charakters** , than do..
<?php if ( get_the_excerpt() <= 30 AND has_post_thumbnail() ) : ?>
<div></div>
<?php else : ?>
<div></div>
<?php endif; ?>
But it seems like that's not the way to read out the length. I was playing around with some definitions that I found like:
<?php if ( the_excerpt() <= 30 AND has_post_thumbnail() ) : ?>
<?php if ( $count($the_excerpt) <= 30 AND has_post_thumbnail() ) : ?>
<?php if ( excerpt_length($count) <= 30 AND has_post_thumbnail() ) : ?>
..but I'm helpless. So..you kind guys. Any idea? | This is more PHP as you need to use `str_word_count()` to count the amount of words in the excerpt. Just note, to be safe, if you allow any tags in the excerpt, you would want to use `strip_tags()` to remove html tags to avoid incorrect word counts.
## EXAMPLE:
echo str_word_count( strip_tags( get_the_excerpt() ) );
If you need to display wordcount on the front end, you can also wrap the above in `number_format_i18n()` to return the integer value according to locale set
echo number_format_i18n( str_word_count( strip_tags( get_the_excerpt() ) ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "count, excerpt"
} |
wp-cli with MAMP shows sh: mysql: command not found
I just installed wp-cli using homebrew and changed the PHP path in .bash_profile to below.
export WP_CLI_PHP=/Applications/MAMP/bin/php/php5.6.10/bin/php
export PATH=$PATH:/Applications/MAMP/Library/bin
When I run this command,
wp core config --dbname="testwp" --dbuser="root" --dbpass="root"
I get this error:
sh: mysql: command not found
Also the output of running wp --info is:
PHP version: 5.6.10
php.ini used: /Applications/MAMP/bin/php/php5.6.10/conf/php.ini
WP-CLI root dir: /usr/local/Cellar/wp-cli/0.21.1
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 0.21.1
I'm not sure if I have framed my question well, so would appreciate all the help. | It looks like you probably don't have mysql in your path. From the command prompt, you should be able to run 'mysql' and enter the mysql interactive environment. If you see something like 'command not found.' then keep working on that path.
There are few different ways to set up your path, I prefer to update the system PATH environment variable so that it become a one-time-thing. (google it - it is a pain on both Windows or Mac).
This post (< suggests your proper path is something like this.. `PATH=$PATH:/Applications/MAMP/Library/bin`
Good luck | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "wp cli"
} |
Plugin option for input box validation
I'm crating a plugin option page from the code below. However, it does not explain how to get validation on the input fields. How do I get validation on `id_number` for NUMBER ONLY?
<
Also, can I add default value to the input? on
`<input type="text" id="title" name="my_option_name[title]" value="%s" />'`
So first time install plugin, it will say something instead of nothing. | You want to set the input's `type` to number for numeric validation. And use the input's `value` to set a default value.
<input type="number" id="title" name="my_option_name[title]" value=123 />
If you just want a hint displayed to the user inside the input, use `placeholder`.
<input type="number" id="title" name="my_option_name[title]" placeholder="Phone Number" /> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, admin menu, validation, options, input"
} |
redirects for removed/deleted woocommerce products
I need to remove some discontinued products from a woocommerce site. I'm just wondering how to go about automating this. I haven't figured out whether to throw a 301, 404 or 410 error, but either way, is there an easy way to automate this for future removed products?
Your help is appreciated. | You can actually use PHP to make redirects, rather than just .htaccess, which has the benefit of allowing you to use variables.
I don't really know woocommerce too well but you could create a redirect similar to this.
Note this is pseudo code. These function calls are fictional but the logic will still apply
function redirect_product() {
$product_status = get_product();
$product_url = get_product_url();
if ($product_status === NULL) {
$URL = $_SERVER['REQUEST_URI'];
if ( $URL == $product_url) {
header( 'HTTP/1.0 301 Moved Permanently' );
header( 'Location: /' ); //redirect to url of your choosing
exit();
} else {
return;
}
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, woocommerce offtopic, seo, automation, customization"
} |
How can I retrieve comments from last 5 minutes for a post?
I need to find comments posted in last 5 minutes. I am using the following query. What should be the value of `before`?
<?php
$postID = get_the_ID();
wp_list_comments(array(
'date_query' => array(
'after' => '5 minute ago',
'before' => ?,
'inclusive' => true,
),
'post_id' => $postID,
'status' => approve,
));
?> | Note that the function `wp_list_comments()` doesn't fetch the comments, only displays them in various ways depending on the input arguments.
You're actually using the `WP_Comment_Query`/`get_comments` input arguments into `wp_list_comments()`.
You could try this instead:
$postID = 12345; // Adjust this!
$comments = get_comments(
[
'date_query' => [
'after' => '5 minutes ago',
'inclusive' => true,
],
'post_id' => $postID,
'status' => 'approve',
]
);
printf(
'<ol>%s<ol>',
wp_list_comments( $args = [ 'echo' => 0 ], $comments )
);
where you can play with the comment output through the `$args` input array.
Check the Codex here.
Note that we can skip the `before` attribute when we use `after` attribute. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "wp query, comments"
} |
Payment methods are not displaying in Woocommerce
I am using **[woocommerce_checkout]** to display checkout section on one page but, payment methods are not displaying in it.
But, when I go to Woocommerce's default checkout page then, payment methods are displaying there. | -You forgot to change **Checkout Page** option.
-Please follow following steps.
1. Go to **_Dashboard -> WooCommerce -> Settings -> Checkout -> Checkout Options_**
2. Under _Checkout Pages_ section you will see **_Checkout Page_** option. Select page in which you have posted `[woocommerce_checkout]`.
3. Click on _Save Changes_.
4. Now go to the page which you have been selected in step 2.
-Hope you will see expected changes in the selected page. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
How to get custom post type post id from slug?
Is it possible to grab the custom post type post id just only from slug?
As much i know we can get from id by using title. But there can be same title in a custom post type so as slugs are unique is it possible??? | You can use `get_page_by_path()` \- don't let the name fool you, third argument is the post type:
if ( $post = get_page_by_path( 'the_slug', OBJECT, 'post_type' ) )
$id = $post->ID;
else
$id = 0; | stackexchange-wordpress | {
"answer_score": 60,
"question_score": 23,
"tags": "custom post types"
} |
Can the wp_posts table have the same slug (post_name) in multiple statuses (post_status)?
I'm using function **get_posts** to retrieve a set of post objects that are my custom post type (CPT). I am counting on being able to programmatically flip these posts between status "publish", "pending" and "draft".
Before I go through the trouble of detecting and "fixing" potential duplicates -- is it even something I have to worry about? Is there any scenario where the same CPT **post_name** can reside in the **wp_posts** table in more than one (row) of differing **post_status** : publish, pending or draft?
(edit) After some experimentation I found that when inserting a post of status "pending", it ignores the post_name parameter - so that ends up being blank in the database. And yes, it will allow many rows in the wp_posts table with the same post_name of '' (blank). I'm sure there's a good reason for this but it is not what I expected that's for sure. | No, multiple posts with the same CPT and post name (slug) are not possible. Someone can work hard and ruin the DB by writing into it some illegal values, but that should not be something you think of when writing your code.
Posts in their initial state are not true posts, they are just place holders, therefor while your observation is valid, it is not really relevant for usual usage pattern of wordpress API, unless once again your aim is to break things. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, plugin development"
} |
To close or not to close php
I have read that it is advised (especially with php 7) to not close the php files with `?>`
Many of my WP php files end like this:
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Should I remove the closing tag and have something like this
<?php get_sidebar(); ?>
<?php get_footer();
at the end of my files? | Yes, please avoid closing PHP tags at the end of the file, not only with PHP 7, but with PHP 5 as well.
Reason is that if you close the tag, anything that is after the tag, even a blank line, will be sent to output and will make PHP to send headers as well preventing cookie to be set, redirect to work, feed to be valid, and so on.
I guess that you ever encountered a message like
> Cannot modify header information - headers already sent by (output started at ...) in ... on line ...
A closing `?>` at end of the file can be the cause. | stackexchange-wordpress | {
"answer_score": 22,
"question_score": 17,
"tags": "php, templates"
} |
how to get pagination link url?
how can I get a pagination link URL instead of a made-up anchor link? currently, I used
<?php next_posts_link(); ?>
<?php previous_posts_link(); ?>
for pagination but it returns `a`, I want to know is there any way to get just the next/prev URL? | If you check out the source, they're both wrappers around `*_posts()`, which in turn are wrappers for `get_*_posts_page_link()` (where the wildcard indicates either `next` or `previous`).
For example, `next_posts()` will echo or return the escaped URL, depending on the first argument:
$escaped_url = next_posts( false /* Don't echo */ );
next_posts(); // Prints escaped URL
Otherwise you can get the raw URL with `get_next_posts_page_link()` and do with it as you wish:
$raw_url = get_next_posts_page_link();
wp_redirect( $raw_url );
// or...
echo esc_url( $raw_url ); | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 7,
"tags": "pagination"
} |
WordPress Feedback popup with date saved into table
Spending now more then 2 days of searching and testing all kind of plugins, I need some help.
I need a Feedback popup plugin with these tasks:
* front-end pop-up with main question + text area for customer answer + submit button
* designable layout
* saves the input data into a table
* text design in admin
* in admin a list of all feedbacks
* email reply to customers
* variable places to start popup on a page
* jquery + ajax + php coded
Maybe someone of you knows a plugin that I can simple recode to fit my needs. Thanks in advance for looking into my question and (I hope) some suggestions. | I would suggest using a combination of two plugins.
1. First a lightbox plugin Lightbox Plugins on the WP Plugin Directory
2. Then using Ninja Forms plugin, which is free Ninja Forms
3. Then create a lightbox following the instructions from the lightbox plugin
4. Then create a form in Ninja Forms
5. And then lastly add the form shortcode inside the lightbox
This is the method I would use except I code my own lightbox and use Gravity Forms, but that is a premium plugin and ninja forms works fine. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, jquery, ajax"
} |
How to change comment texts that has a specific comment_ID - Hook into comment
Say, I want to change the comment text where comment_ID = 10 or 19. I don't want them to be updated in the database. Just in the frontend, it'll show a custom text instead of original comment content.
Is there any hook that helps? | You can try the `get_comment_text` filter. Here's an untested example:
/**
* Override comment text for comments with ID 10 or 19
*/
add_filter( 'get_comment_text', function( $text, \WP_Comment $c, Array $args )
{
if( ! is_admin() && in_array( $c->comment_ID, [ 10, 19 ] ) )
$text = __( "You've Just Been Erased!" );
return $text;
}, 10, 3 );
where the `\WP_Comment` class will be introduced in WordPress 4.4
For WordPress < 4.4 we would just have to remove the `\WP_Comment` _type hint/declaration_ :
/**
* Override comment text for comments with ID 10 or 19
*/
add_filter( 'get_comment_text', function( $text, $comment, Array $args )
{
if( ! is_admin() && in_array( $comment->comment_ID, [ 10, 19 ] ) )
$text = __( "You've Just Been Erased!" );
return $text;
}, 10, 3 );
and this would also work in +4.4. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments"
} |
Can a shortcode return its own name?
Assuming there is some function or variable that allows the shortcode access to its name, and for sake here I will term that `$scName`, is something like this possible:
function test_return_shortcode_name( $atts ) {
return $scName;
}
add_shortcode( 'myName', 'test_return_shortcode_name' );
And so for this basic example, this shortcode:
[myName]
Which would return the actual name as text
myName
Does such functionality exist to access the designated name from _within_ the function associated to it? | A shortcode can access its own name - it is supplied as third parameter to the shortcode's callback function, just like that:
function test_shortcode_callback( $atts = array(), $content = null, $tag ) {
return $tag;
}
add_shortcode( 'test_shortcode', 'test_shortcode_callback' );
// So running this shortcode
[test_shortcode]
// Will return this
test_shortcode | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode"
} |
If no image, bigger text
Working on a categories/ front page, I would like to display an image and title for posts with an image. When there is no image, it leaves a big blank space -- looks empty, of course ... So I'd like to use bigger text for the title if there is no image.
Has anyone found a way to do so with WordPress?
My code is:
<div class="feature-section-1">
<?php $posts = get_posts( "tag='tagtitle'&numberposts=1" ); ?>
<?php if( $posts ) : ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<a href="<?php echo get_permalink($post->ID); ?>" >
<h3><?php echo $post->post_title; ?></h3>
<div class="false-excerpt-div"><?php the_excerpt(); ?>
</div>
<?php if ( has_post_thumbnail()) : the_post_thumbnail('columner-thumb'); endif; ?>
</a>
<?php endforeach; ?>
<?php endif; ?>
</div> | This should work.
<div class="feature-section-1">
<?php $posts = get_posts( "tag='tagtitle'&numberposts=1" ); ?>
<?php if( $posts ) : ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<a href="<?php echo get_permalink($post->ID); ?>" >
<?php if ( has_post_thumbnail() ): ?>
<h3><?php echo $post->post_title; ?></h3>
<div class="false-excerpt-div"><?php the_excerpt(); ?></div>
<?php the_post_thumbnail('columner-thumb'); ?>
<?php else: ?>
<h1><?php echo $post->post_title; ?></h1>
<div class="false-excerpt-div"><?php the_excerpt(); ?></div>
<?php endif; ?>
</a>
<?php endforeach; ?>
<?php endif; ?>
</div> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php"
} |
How to output the title of the blogs home page
I am using a static frontpage and a page for my blogposts. In my header.php I want to display the title of the selected page of my blogposts.
For example:
<?php
if( is_home() )
echo '<h1>' . get_the_title() . '</h1>';
?><nav>
...
</nav>
But of course `get_the_title()` returns the first element of the displayed posts and not of the page itself.
How can I display the title of the assigned home page? | You can make use the queried object to return the title of the page used as blogpage
You can use the following: ( _Require PHP 5.4+_ )
$title = get_queried_object()->post_title;
var_dump( $title ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 0,
"tags": "wp query, title, homepage, get the title"
} |
How can I easily add code under the <body> tag without using hooks?
I need to trying to get the Facebook SDK for JavaScript code inserted just after the tag.
What's the easiest way to do this? | Check your theme files (probably header.php), you will find starting `<body>` tag. Just paste the code below it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, code"
} |
Passing arguments to wp_list_comments callback function
One can customize single comment markup using the `callback` argument in `wp_list_comments` like this:
$args = array( 'callback' => 'my_callback', 'avatar_size' => 48, 'type' => 'comment' );
wp_list_comments( $args );
The question is, how to pass arguments to that `my_callback` function? Already it gets three:
function my_callback( $comment, $args, $depth )
But I need to add my own 4th argument | Finally I figured it out. you may simply add your arguments to the `wp_list_comments` as associative `key` => `value` pairs like this:
$args = array( 'callback' => 'my_callback', 'avatar_size' => 48, 'type' => 'comment', 'arg1' => $arg1 );
wp_list_comments( $args );
and then in your `my_callback` you have:
function my_callback( $comment, $args, $depth )
where you have access to `$arg1`; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "comments, comments template"
} |
Archives widget doesn't work?
I've seen the same thing in every theme I've tried: Main page shows ten (or more) most recent posts. Click on a month in the archives list, more than a year back, and Wordpress generates the exact same list of posts. | You most probably have a plugin that either uses `query_posts`, are have a bad filter and/or query that is altering the the main query object ( _`$wp_query`_ ) as you have this issue across all themes that you have tested.
You should deactivate your plugins one by one and check which one/s are causing the issue. Also, turn debug on and look for obvious errors | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "archives"
} |
Wordpress shortcodes are not working
I am trying to use shortcode in wordpress. but its not working. I am new at this kind of job.
My codes are:
This is a post with short code ......
[contact-form]
[contact-field label="Name" type="name" required="true" /]
[contact-field label="Email" type="email" required="true" /]
[contact-field label="Website" type="url" /]
[contact-field label="Comment" type="textarea" required="true" /]
[/contact-form]
But it doesn,t work. It print the code as it is. Whats wrong with my code?
 does offer some default shortcodes that you can reference.
> [audio]
> [playlist]
> [wp_caption]
> [caption]
> [embed]
> [gallery]
> [video]
[contact] is not one of them. You seem to be referring to the Shortcodes offered by Wordpress.com however these shortcodes are peculiar to sites hosted on Wordpress.com - they will not work in your Wordpress application.
To call other shortcodes you will need to choose a plugin that includes contact shortcodes, or write your own, as described in the Wordpress Shortcode API. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "shortcode"
} |
Notify Wordpress Site I Have Linked To Them
I have noticed that when a Wordpress site puts a link to my site in a post it shows their website in the comments section of my site.
I'm wonder how could I make my PHP application do this? I mean when I link to a Wordpress site in my application it will show up in the comments section on the site I linked to automatically. I've tried to search on Google how to do this but I can't find anything. | The term you need to search for is "Pingbacks" (and maybe "Trackbacks", but the former is better as it is less vulnerable to spam abuse).
It is an XML-RPC request. You can find the specification here.
Looking at github there seem to be some bare metal PHP implementations, but as I haven't used any of them I am not going to link to them directly, but you can easily find them via Google.
Also be aware that you can only notify a site. If it cares about the notification as well as if and how the link is display is of course out of your control. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, comments, pingbacks"
} |
What is the source outline for a basic word press plugin?
I'm a fairly skilled PHP developer, and watching a tutorial on how to build a WP plugin, with the intention to get my name out there. What is the outline for a WP plugin that includes database calls?
I could type it from the video, but I'm thinking it would be easier to just do a copy/paste of the plug in similar to how you build an html page. example:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
The video I watched was: < | Depends on the plugin you want to create really but ultimately you should follow the WordPress Plugin Handbook / Best Practices.
You'll want to start with the WordPress Plugin Boilerplate ( tutorial ) or WordPress Plugin Boilerplate Generator ( tutorial ).
Also, a general search for wp boilerplate plugin should get you on your way.
As for the database part, you just need the structure to start with then find specific code to interact w/databases. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "plugins, php, plugin development"
} |
Split Page Links
My client wants a initial page that is split in two, with a logo of her ministry website on one side and a logo of her business on the other side. When you then click the desired logo it takes you to the corresponding website.
How can I accomplish this in WordPress? Is there even a technical name for this? All I can think of is a splash page. | Something like this should get you started.
**CSS:**
.home div {
display: inline-block;
width: 50%;
}
.home a {
display: table-cell;
text-align:center;
vertical-align: middle;
}
**HTML:**
<div class="home">
<div><a href="site.com"><img src="path-to-logo-1"></a></div>
<div><a href="site-two.com"><img src="path-to-logo-2"></a></div>
</div>
If it's literally a single page site that only links off to two other sites, setting up WordPress for it is absolutely overkill. Download HTML5 Boilerplate or similar, stick something akin to the above into the HTML file and stuff it on the server. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages"
} |
Turn revisions off in plugin instead of config.php?
Is there a function to set WP_POST_REVISIONS from a plugin instead of having to do it in config.php? I was thinking of doing this:
runkit_constant_redefine( 'WP_POST_REVISIONS', 0 );
but that puts a dependency on runkit being compiled in with PHP which I'm not sure is usual/typical.
I want to turn revisions off completely and I'd like my (narrow use, special purpose) plugin to be as "turnkey" as possible; not requiring other tweaks or manual adjustments. | 1. Create a no-revs.php
2. Set the contents to `<?php defined('WP_POST_REVISIONS') or define ('WP_POST_REVISIONS', false);`
3. Place it in the Must Use Plugins Folder located at `wp-content/mu-plugins`.
Be warned; It is recommended that you to have at least 3 post revisions to avoid any loss of data. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "plugin development, wp config, revisions"
} |
Child theme template file will not load
I have a child theme that will load my style.css file but will not load my php template file.
I got this template file by copying and pasting it from the parent directory into a new file with the same file name and everything. Then I edited one line of text as a test and loaded the file into the root of the child theme directory. I refreshed my site but no change could be seen.
The theme is zerif-lite and I'm not sure why this is happening | Place a directory in the child directory with the name of the directory from the parent directory where the .php template file was originally found. Then place the modified template in there. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 2,
"tags": "templates, child theme"
} |
$_POST empty in using new php file added to theme
I am using a theme which handles form data with jquery (a handler function defined).I have added a new php file to theme (using it in as template in a wordpress page, also registered with rewrite rules).
*The Problem is when I submit form, handler function receives no data ($_POST empty). Also Firefox popus up a message "To display this page, Firefox Developer Edition must send information that will repeat any action". This message pops up because javascript tryies to reload page using this function :"jQuery.post(form.attr('action'), data, function(response) " In other template files which forms works correctly,this function doesnt execute.
I have checked jquery handler and it seems it submits form correctly.I dont know what problem is.
Other template forms have no problems.
Does wordpress core cant send data from jquery to handler function?
Sorry for my poor english. Thanks alot | SOLVED by somebody:
“if my form pointed to a directory:
<
then my POST data disappeared and $_POST was empty. If I pointed to a specific file: <
Then it worked properly."
ps: God bless him. :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, ajax, hooks, forms, rewrite rules"
} |
How to change all the guid in posts table?
Recently I have transferred my WordPress from development server to live server. I noticed that I have to change all the "guid" with live domain url. Is there any mysql query or simple function available to change it easily. | It should be something like:
UPDATE wp_posts SET guid = REPLACE(guid, 'oldurl.com', 'newurl.com') WHERE guid LIKE '
* `oldurl.com` \- Previous URL shown in wordpress settings > general options
* `newurl.com` \- New URL | stackexchange-wordpress | {
"answer_score": 24,
"question_score": 10,
"tags": "posts, guids"
} |
Change colour of table td based on value
I have this code in my table calling in a number
<tr>
<td>Total: <?php echo $total_credit;?></td>
</tr>
I would like to change the background colour or the text colour depending on whether this value is equal to or higher than 2, is there an easy way I could do this with an If statement?
Thanks for any help in advance! | Here is the updated code with condition
<tr>
<td <?php if($total_credit >= 2): ?> style="background-color:#000000;" <?php endif; ?>>
Total: <?php echo $total_credit;?>
</td>
</tr>
Change #000000 to appropriate color code. Then the background color will be changed. Use same logic for changing the text color. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, table"
} |
Remove Permalink From Admin Edit Post
Is there any way how to edit the title field in post.php?
**this field** :  {
return '';
}
add_filter( 'get_sample_permalink_html', 'hide_permalink' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "admin, hooks, title, post editor"
} |
wp-cli Enabling Maintainance Mode
During theme or plugin upgrades, maintenance mode is enabled and then disabled once complete.
Is it possible to manually enable / disable maintenance mode?
`Enabling Maintenance mode... Downloading update from xxxx Disabling Maintenance mode...` | WP-CLI now has native commands for it.
# Activate Maintenance mode
$ wp maintenance-mode activate
# Deactivate Maintenance mode
$ wp maintenance-mode deactivate
See `wp-cli/maintenance-mode-command` for more information. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 11,
"tags": "wp cli"
} |
How do I hide a specific div class inside <style>?
I'm working on this web page: < and I'm trying to hide the island chain you see on the right. "class="hawaii-map"
<style>
#feature {
display:none;
}
.copyright {
position:fixed;
bottom:0;
}
p {
color: #807C78;
position:fixed;
bottom:0;
}
</style>
I can hide the piece of the page using the following, but I'm only trying to hide the island chain. Also when I apply #hawaii-map as the class, nothing happens.
Can you help me?
;
display: inline-block;
}
More info
* <
* <
* < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "menus"
} |
enumerating custom taxonomies?
I made this function that displays tags as an image grid
function execute_taxography() {
$wpbtags = get_tags();
$output.= '<div class="grid"><div class="taxography-grid"><ul>';
foreach($wpbtags as $tag) {
$output.= '<li class="item"><a href="'. get_tag_link($tag->term_id) .'" style="background-image: url(\' . $tag->slug . '.png\')"><span class="count">'. $tag->count .'</span><span class="taxography-name">'. $tag->name . '</span></a></li>';
}
$output.= '</ul></div></div>';
return $output;
}
Now I made a custom taxonomy named "book" and I want to display it in the same way as the tags but I'm stuck on the loop!
Any ideas? | `get_tags` is just a wrapper around the more general taxonomy function `get_terms`. So you'll get the result you need with this:
function execute_taxography() {
$wpbtags = get_terms( 'books' );
$output.= '<div class="grid"><div class="taxography-grid"><ul>';
foreach($wpbtags as $tag) {
$output.= '<li class="item"><a href="'. get_term_link($tag->term_id, 'books' ) .'" style="background-image: url(\' . $tag->slug . '.png\')"><span class="count">'. $tag->count .'</span><span class="taxography-name">'. $tag->name . '</span></a></li>';
}
$output.= '</ul></div></div>';
return $output;
}
I've also replaced function `get_tag_link` with `get_term_link`.
Read about `get_terms` at < Read about 'get_term_link` at < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, custom taxonomy, loop"
} |
Installing other applications alongside WordPress multisite and configuring dns routing
I have configured a subdomain on my server and in DNS at my registrar as I have done many times. I don't want this particular subdomain to use my multisite WordPress install but all requests are being routed to `
Can anyone suggest what configuration step I have missed to prevent WordPress from receiving requests to subdomain.mysite.co.uk ?
How can I install other applications alongside a WordPress multisite install correctly?
This particular server is Ubuntu 14.04 running Apache2.x
I feel that this **DOES** relate to WordPress as the server configuration was previously set up only for WP multisite and I feel other WP admins would benefit from this knowledge. | codecowboy has reports in the comments for this question that the issue has been resolved:
> Running `a2ensite` resolved the problemm so presumably I had done something wrong with my Apache config. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, subdomains, apache, dns"
} |
Associating special meaning with user id 0
I'm writing a plugin that creates a custom table holding data which is linked to a user account with a `user_id` field. Now if that users account would be deleted for any reason I would like to set that `user_id` field in my custom table to `0` to keep the stored data in an anonymized fashion.
Since the first user `ID` is `1` and counted upwards from there I would assume this is save. Is there any reason why this might have unwanted side effects?
Also, if I would add key constraints to my custom table this would obviousle be a problem when `0` is not existent in `wp_users`. Would it be hazardous to add a fake user record with id `0` to `wp_users`? | I think I found the most semantic solution: If I want to relate a given row of data to "nowhere", `NULL` is the best value to reflect that. And it even works with constraints on the field! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, database, id, customization"
} |
How to show all available images in WP's media library when using the Polylang plugin?
It seems that depending on which default language I've set Polylang to, all my uploaded images are isolated so that I can only pick them when I'm editing posts in the default language.
I have a lot more images shared/in-common between English and French posts than images specific to a single language.
Is there any option to show all images regardless of which language I'm currently editing in Wordpress?
 if so, I may have an entirely different problem on my hands.
Is there a way to simply show ALL assets? | From this post at wordpress.org/support, the user **Chrystl** points out:
> If don't need to translate your media titles, uncheck this option:
>
> In **Languages > Settings tab > Media: "Activate languages and translations for media"**.
>
> And you will access to your _**entire library**_ by clicking on "Add media" and "Set featured image".
And that indeed did the trick for me! :) | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 10,
"tags": "uploads, media, media library, plugin polylang"
} |
Trouble figuring out how to get my button to submit comment
I have a text area in the sidebar (sidebar-chat.php) of my posts page with an input that is an image. When this image is clicked, the comment is supposed to submit. I am just having trouble figuring out how to make this happen. Below is a screenshot of what it looks like, as well as the HTML. Am I supposed to add a function to functions.php to get this to happen? Any advice would be great!
; ?>/images/sign-in.png" />
</div> | Try this. You were missing the tags and the "type" attribute for the tag. The php tag at the bottom echo's the result that was input in the textarea. Read this < it should help you get started.
<div class="font-wrap">
<div class="wrapper">
<form action="" method="post">
<textarea name="comment" id="comment" class="talk-bubblecomment" tabindex="4" placeholder="Enter comment..."></textarea>
<p class="sign-in">
Post a new comment
</p>
<input type="submit" value="Submit Comment" />
</form>
<?php echo "$_POST[comment]";?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php, functions, comments, javascript"
} |
Remove JSON API links in header html
Does anyone know how to remove the WordPress JSON API links in the header tag?
<head>
...
<link rel=' href=' />
<link rel="alternate" type="application/json+oembed" href=" />
<link rel="alternate" type="text/xml+oembed" href=" />
</head>
I'd like to avoid using a plugin. If possible, is there a way to remove them with the remove_action function?
remove_action( 'wp_head', 'rsd_link' ); | I see in filters.php "add_action( 'wp_head', 'rest_output_link_wp_head', 10, 0 )" Which makes me think this should do the trick to remove `rel='
remove_action( 'wp_head', 'rest_output_link_wp_head' );
The rest... * _cough_ * seem to be in default-filters.php
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
To remove the rest_output_link_header
remove_action( 'template_redirect', 'rest_output_link_header', 11 );
Reference
* wp_oembed_add_discovery_links
* rest_output_link_wp_head
* rest_output_link_header | stackexchange-wordpress | {
"answer_score": 42,
"question_score": 39,
"tags": "themes"
} |
Calculate all custom field values in the post loop
I have a custom post type named 'ordered_food' and the custom field named 'price', Alhough I can print out all the values, I don't know how to plus and calculate the total price. Because it's already in the wordpress custom post type loop.
;
$total_amount += get_post_meta($post->ID, 'custom_field2', true);
$total_amount += get_post_meta($post->ID, 'custom_field3', true);
//loop end
echo 'Total: '.$total_amount; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom field, loop"
} |
WP REST API - reading custom post type
I have a WP site that runs on WP version 4.3 and using a plugin WP REST API version2-beta9. I have a custom post type **animals** which has an ACF select field of **class** which has values like mammals, reptile, etc.
If getting values of custom post types is available for WP REST API, is it possible that I can **GET** request on my endpoint to retrieve values of all **mammals** under the **animals** custom post type? If yes, how do I do that? | I have checked the WP REST API documentation for the version2-beta9, it is not yet implemented so I guess I have to code my own plugin to work around on it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, wp api"
} |
How to only show page id as body class?
Some call it light OCD, some might call it security risk. I just don't like how it throws it all in there, especially template names.
How to only assign page id or even better - slug?
Note that this is in header template, it should output current page's id / slug.
All "professional", high quality WP sites I've examined, doesn't have that kind of mess.
<body <?php body_class(); ?>>
|
v
<body class="home page page-id-495 page-template page-template-template-home-slideshow page-template-template-home-slideshow-php logged-in"> | Honestly, it's source code. The only people who see it are you and other developers. Anybody casually visiting your website will never know or understand this stuff so really there's no harm keeping it there. _Buttttt..._ if you want to get rid of it you could filter `body_class`:
function custom_body_class( $classes ) {
global $post;
if( isset( $post ) && is_object( $post ) ) {
$classes = array( "page-{$post->ID}" );
}
return $classes;
}
add_filter( 'body_class', 'custom_body_class' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, html"
} |
Query Multiple values for same key
I have tried to get 2 different posts having the values in `$al`. I can retrieve the posts one at a time but fail to get both together:
$al = array('51.66963','51.60652');
$meta_query[] = array(
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'estate_property_google_maps',
'value' => $al['0'],
'compare' => 'LIKE',
),
),
array(
'key' => 'estate_property_google_maps',
'value' => $al['1'],
'compare' => 'LIKE',
),
); | Shouldn't it be like this (doc)?
$meta_query[] = array( 'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'estate_property_google_maps',
'value' => $al['0'],
'compare' => 'LIKE'
),
array(
'key' => 'estate_property_google_maps',
'value' => $al['1'],
'compare' => 'LIKE'
),
) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "meta query"
} |
Change user's display name programmatically
I'd like to change a user's display name using this code snippet in my theme's `functions.php` file:
$user_id = 672;
$display_name= 'Les Yeux';
$user_id = wp_update_user( array( 'ID' => $user_id, 'display_name' => $display_name ) );
This is adapted from this topic in the codex: <
But I can't get it to work. It didn't change anything. Did I miss something? | Just pasted your code into my `functions.php` with a different ID and checked the user's page in `/wp-admin/user-edit.php` \- it works, the value in `Display name publicly as` field is updated.
Most likely something is wrong with your output on the user page. Check your template file. Or, if you can't find the problem, edit the question and update it by pasting only the relevant code from your template - **not** the entire template. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "users, username"
} |
Images showing in editor but not in post
Images are showing up in the editor, but not in the post. What's weird is that on initial page load, the images flash into existence and then disappear with a broken image icon. Here is an example post:
<
This site is brand new on Wordpress.com. Everything was imported from an pre-existing self-hosted WordPress site (I used the built-in export tool to generate an XML file). It looks like the images did make it over in the import.
On this post, in the browsers web inspector, it shows the source of one of the misfiring images as...
<
...which loads fine on its own, but not in the post itself. So confusing! | It shows on your new site that it reflects the old domain ` if you are not planning to use your domain ` you need to re import your xml file to and do a find and replace of the string from ` to ` before importing them.
If you will be using your domain ` in the wordpress.com site instead of the free tier appending the `wordpress.com` in the URL, I think that should automatically fix your problem | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "images, wordpress.com hosting"
} |
query_posts by category_name and custom taxonomy
I want to display posts filtered by category_name and custom taxonomy-term:
I have
function channel_init() {
// create a new taxonomy
register_taxonomy(
'channel',
'post',
array(
'label' => __( 'Channel' ),
'rewrite' => array( 'slug' => 'channel' ),
'hierarchical' => true,
'capabilities' => array(
'manage__terms' => 'edit_posts',
'edit_terms' => 'manage_categories',
'delete_terms' => 'manage_categories',
'assign_terms' => 'edit_posts'
)
)
);
}
add_action( 'init', 'channel_init' );
Imagine i have a channel-term "news". And a catgory_name "music" - Now i want to query:
query_posts( array( 'channel' => 'news', 'category_name' => 'music') );
channel is ignored category is filtered only. | $args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'channel',
'field' => 'slug',
'terms' => array( 'news', 'comedy' ), //this is by slug
),
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 103, 115, 206 ), //this is by id
)
)
);
$query = new WP_Query( $args );
That could be great if you use WP_Query than query_posts. But result are the same. WP_Query is more flexible :). Don't forget to check more in deep about query. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, custom taxonomy, query posts"
} |
wp enqueue, how to prevent duplication when same script is registered with different handles
I read that wp enqueue prevents duplicate script to be loaded. But, what happens when same script ( say bootstrap.js) is loaded by 2 different plugins with 2 different handles using wp enqueue ? | JS/CSS Duplication by itself is not bad. It makes the HTML a little bigger nut the browser should in most cases cache the first request and not serve the second one (most cases === unless it is a very badly configured server)
The real problem with duplication is trying to load two different versions of the same file (say two different versions of jQuery), and this is what the API helps to solve by providing a handle to the version which already exists as part of core.
The best thing in your case is to probably think again why do you even need bootstrap in a plugin, why the admin CSS and JS is not enough for you. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp enqueue script"
} |
TOO MANY REDIRECTS ERROR when redirecting buddypress register page to WordPress sign up
I have a problem with using Wordpress registration page instead of BuddyPress page, that when I use the snippets given in github and add them to a file named (bp-custom.php) or functions.php file I get an error telling me that there are too many redirects.
I was adviced to remove the second snippet of the link and this removed the error from the page but yet I get an empty buddypress registration page!
Any ideas on how to solve this problem? | Had the same problem Found this solution in my intense google search:
/ hacks and mods will go here This Version is plugin folder
/**
* Disables BuddyPress' registration process and fallsback to WordPress' one.
*/
function my_disable_bp_registration()
{
remove_action( 'bp_init', 'bp_core_wpsignup_redirect' );
remove_action( 'bp_screens', 'bp_core_screen_signup' );
}
add_action( 'bp_loaded', 'my_disable_bp_registration' );
add_filter( 'bp_get_signup_page', "firmasite_redirect_bp_signup_page");
function firmasite_redirect_bp_signup_page($page )
{
return bp_get_root_domain() . '/wp-signup.php';
}
Solution:
CHANGE
return bp_get_root_domain() . **'/wp-signup.php'**;
TO
return bp_get_root_domain() . **'/wp-login.php?action=register'**;
All is working perfect now | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "errors, buddypress, redirect"
} |
What does wp-embed.min.js do in WordPress 4.4?
**Question**
1. What does the `wp-embed.min.js` file do? I noticed it is added to the end of my blog page footer.
2. How can I get rid of it?
**Effort**
After some googling and I found Embeds on the Codex. Why does WordPress think I want to add videos, etc. to my page by default?
**Environment**
WordPress 4.4 | ## What is it?
It is responsible for converting links into embed frames.
For example you can paste a Youtube video link into the editor content section and the Youtube embed will be generated for you when your page is viewed.
More information on WordPress Documentation
## How to get rid of it?
I could finally get rid of that using this:
function my_deregister_scripts(){
wp_deregister_script( 'wp-embed' );
}
add_action( 'wp_footer', 'my_deregister_scripts' ); | stackexchange-wordpress | {
"answer_score": 82,
"question_score": 67,
"tags": "javascript, wp enqueue script, embed, footer"
} |
Not sure if I should create multiple custom post type
I am working on a projects that has different tutorials, such as js, html, css and etc.
I was initially thinking to create one custom post type for each tutorials, but after some research, I think maybe it is better to create one custom post type called Tutorial, and have different categories under it, like js, html, css and etc.
I am not sure which approach is better. I am more concern about the performance and SEO. Can someone share the thoughts, pros and cons with each approach.
Thank you. | You shouldn't create multi custom post type, Think your project scope clearly.For Tutorials like html,css, js or other tutorials, you should create only tutorials custom post type. So that
yourdomain.com/tutorials
yourdomain.com/tutorials/html/
yourdomain.com/tutorials/js
It's more readable and good for SEO. Analyze the project flow clearly and then you could configure well for that. Good luck in codes :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, categories, seo"
} |
My simple custom shortcode is not longer working (possibly due to upgrade to WordPress 4.4 ?)
I have a simple function in functions.php that creates a custom shortcode:
function my_line_break() {
return "<br>";
}
add_shortcode( 'new line', 'my_line_break' );
Now, I don't know if this happened after upgrading to 4.4 but it's not longer working and pages just render `[new line]` in plain text.
Anyone can help with this? I looked at < but I'm not sure it relates?
P.S. I know this wouldn't be the right way to handle line breaks, but I did it as a way to make life simpler for my customer (so as a little side question, if there is a valid and simple to use alternative, could you please let me know it so I can also bypass this problem completely?). | Converting the comment to an answer,
please rename your Shortcode to not contain spaces (`new_line`):
function my_line_break() {
return "<br>";
}
add_shortcode( 'new_line', 'my_line_break' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, shortcode, line breaks"
} |
Retrieve value of a category's custom field
Using the 'Advanced custom fields' plugin I have added a field to every post category that is called 'color' and it works just fine.
Now inside the loop I need to retrieve the value of the 'color' field, I have followed many other tutorials, but I could not achieve the result needed.
Here is the exaple of how the loop is set up:
while ( $projects->have_posts() ) {
$projects->the_post();
$category_classes = array();
$categories = get_the_terms( get_the_ID(), 'project_category' );
if ( $categories ) {
foreach ( $categories as $category ) {
$categories_included[] = $category->term_id;
}
}
Now in perfect scenario, I need to get the 'color' of a category inside the foreach loop.
Any help or guidance is much appreciated. | < prety much covers what you're after I believe.
So in your example
while ( $projects->have_posts() ) {
$projects->the_post();
$category_classes = array();
$categories = get_the_terms( get_the_ID(), 'project_category' );
if ( $categories ) {
foreach ( $categories as $category ) {
$categories_included[] = $category->term_id;
$color = get_field('color', 'project_category_'.$category->term_id);
}
}
You can also pass a term to get_field and the_field, so you could also use the following depending on your version of ACF as I believe much older versions don't support passing terms
$color = get_field('color', $category); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, custom taxonomy, custom field, advanced custom fields"
} |
POSTS list in WordPress by views
I need a code that causes: `<?php while ( have_posts() ) : the_post(); ?>` List according to the amount of VIEW, is like to list popular posts only that it will enter the table **mh_postmeta** , and list according to who has the most **view**.
;
$query = new WP_Query( $args );
//...and on with the loop
<?php while ( have_posts() ) : the_post(); ?>...
Limiting this behavior to category 3 is pretty easy but how go about it depends on the context and your template setup.
More on `orderby` in the WP Codex | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, order, phpmyadmin"
} |
How do I Turn This Into An if statement?
PHP noob here. I've got this query I've written to get the information of all child pages of the page you're currently on:
<?php
$pages = get_pages('child_of=1015&sort_column=post_title');
$count = 0;
foreach($pages as $page)
{ ?>
<div class="position-info"><h4><a href="<?php echo get_page_link($page->ID) ?>"><?php echo $page->post_title ?></a></h4></div>
<?php
}
?>
But I don't know the correct syntax to turn this into an if statement, followed by an else statement so I can say "There's no content here. Check back later." Or something like that.
This query is inside of the page's main loop.
Can any PHP masters out there help? | Here's the code I got working, thanks Manu!
<?php
// Vars
$pages = get_pages('child_of=1015&sort_column=post_title');
$count = 0;
if (!empty($pages)) {
foreach($pages as $page) { ?>
<div class="position-info"><h4><a href="<?php echo get_page_link($page->ID) ?>"><?php echo $page->post_title ?></a></h4></div>
<?php
}
} else {
echo '<div class="position-info"><h4>Bummer! Looks like we’re fresh out of internships. Check back often!</div>';
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, loop, child pages, 500 internal error"
} |
How to remove rest api link: in http headers?
i would like to remove the "link:" line added to the http headers since wordpress 4.4
here is a
curl -I killcandida.org
here is the output extract of the line that i would like to delete:
Link: < rel="
Note that i don't talk here about html headers but http headers. | The output is generated by the rest_output_link_header(). This function is used in two actions, **wp_head** and **template_redirect** in **default-filters.php:@line234**. You can remove the function from those hooks to remove the output you wanted to remove. Put the following codes in your theme's functions.php to achieve the desired result.
remove_action( 'wp_head', 'rest_output_link_wp_head', 10);
remove_action( 'template_redirect', 'rest_output_link_header', 11);
* rest_output_link_header
* Remove WordPress JSON API links in header html
Both actions are defined in `ABSPATH/wp-includes/default-filters.php` under `// REST API filters.` | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 10,
"tags": "headers, http, http api, rest api"
} |
Restrict backend but allow to use post.php?action=delete&post=POSTID from front-end
Restrict backend.
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
if ( is_admin() && ! current_user_can( 'administrator' ) && !( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}
This code will restrict backend for all users roles except for admin which is what I want. However, I want to allow Authors to delete their posts from front-end using ` link on Delete button.
Is it possible to exclude that link for the redirect? So authors can delete their posts from front-end? | This will allow you to access `post.php` and still restrict the back-end. You need have action, action name as `delete`, post key and value, and wpnonce kay and value. Otherwise, it will redirect you to homepage.
function disable_wp_admin() {
if ( ! is_admin() )
return;
if ( current_user_can( 'manage_options' ) )
return;
if (( current_user_can( 'edit_posts' ) && defined( 'DOING_AJAX' ) && DOING_AJAX ) )
return;
if ( 'post.php' == isset( $_REQUEST['action'] ) && 'delete' == $_REQUEST['action'] && isset( $_REQUEST['post'] ) && isset( $_REQUEST['_wpnonce'] ) )
return;
$redirect_to = home_url();
wp_redirect( $redirect_to );
exit;
}
add_action( 'init', 'disable_wp_admin' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, user roles, front end, content restriction"
} |
WordPress keeps redirecting to an unsecure connection?
I'm trying to login to my site (clicked the Edit button) on secure connection and now it redirected to HTTP login page.
Why did this happen and how can I **_suggest_** (force) to WordPress to always use HTTPS? | For individual sites go to the settings page and update the SITE URL and Address.
For multisites / network installs I must enter enter it in the Network Settings Page or if it's not there enter it manually in the `wp_config.php` page.
I'm also making sure that any one that enters http instead of https is redirected to the https version of the site. I can do this on the domain name / SSL settings page or in the .htaccess file in the root of the blog install. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "login, https"
} |
Difference between wp_list_categories and get_categories
Whats the difference between the `wp_list_categories` and `get_categories`?
Wordpress codex says
> use get_categories if needs a function that does not format the results
what format is this referring to? Will it affect the performance if I use the other one? And if i want to display all the hierarchical custom taxonomy links on a page, should I use those two functions or use another one? | `wp_list_categories` gives you HTML markup of links (`<a>`) to the categories while `get_categories` just returns the data to be used for whatever you wanted.
But actually Pieter is right, in such cases just give it a try, nobody will get hurt ;) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
WordPress is Inserting images into Post as HTTP and not HTTPS
I've logged into my site in HTTPS and I'm editing on a specific post. I've dragged an image to the edit window and am now inserting an image.
The thing is WordPress is inserting the image as HTTP instead of HTTPS. It shows the URL as HTTP clearly and uneditable.
;
// remove 'http:' part from any mention of the site url
function wpse_211864($content) {
return str_replace(siteurl(),str_replace('http:','',siteurl()),$content);
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "images, ssl, https"
} |
Prevent WordPress from adding image' title automatically
I wrote a plugin that set default title for all non-set (empty) titles and leaves the titles set manually (non-empty).
The problem is when I upload new photos (to gallery), WordPress by default set the title to file's name. How Can I disable it and **force WordPress to use empty string as default image title**? | You can try the following to clear the image attachment's title when it's _inserted_ but not _updated_ :
/**
* Empty the image attachment's title only when inserted not updated
*/
add_filter( 'wp_insert_attachment_data', function( $data, $postarr )
{
if(
empty( $postarr['ID'] )
&& isset( $postarr['post_mime_type'] )
&& wp_match_mime_types( 'image', $postarr['post_mime_type'] )
)
$data['post_title'] = '';
return $data;
}, 10, 2 );
Here we use the `wp_insert_attachment_data` filter to override the attachment's title if the attachment's `ID` is empty and the mime type is an _image_ type according to `wp_match_mime_types()`. A simple `'image' === substr( $postarr['post_mime_type'], 0, 5 )` check might work as well. You could even target a given mime type, like `image/jpeg`. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 11,
"tags": "images, gallery, title"
} |
Correct way to hide pseudo pages from being shown?
The homepage on a site we've developed has four pieces of content: the parent page and three further "pages" of text which we bring into the parent page using PHP. Call them Foo, Bar1, Bar2, Bar3 if you like.
Maybe this is or isn't the correct way to solve the problem of a complex page but it works for us and for the client and he's used to it now.
 redirecting mysite/bar1 to mysite/foo in htaccess
OR
2) via our SEO plugin (Yoast) apply a robot noindex
But I'm asking here which approach is more correct or whether there's a better way? | Well those are two different things:
1. A redirect means they are not accessible any more at all.
2. noindex just means that search engines ignore it while it is still accessible if you access the URL.
So I'd recommend option 1. This is a simple way of doing this that you can improve an. (E.g. this expects to have a static front page set and doesn't handle any other situation)
function wpse_211889_template_redirect()
{
if ( ! is_page() ){
return;
}
$frontpage_ID = get_option('page_on_front');
global $post;
if( $post->post_parent && $frontpage_ID === $post->post_parent )
{
wp_redirect( home_url() );
exit();
}
}
add_action( 'template_redirect', 'wpse_211889_template_redirect' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "redirect, google, robots.txt"
} |
Replace / Remove Shortcode after 1st run / post
I want to use a shortcode to replace it with an image form a url.
My idea:
[shortcode url="
I post this shortcode usinbg IFTTT. After publishing the article the shortcode should be replaced by the image. But the image should come from my "local" library. So the shortcode should download the image, replace it self with a html tag for the image in the library ... that's it :-D
Is it possible to use a shortcode that way? How? | The sample post should be the content.
> Samplepost {IFTTTImageFetch=" some stuff ..asd asd asd
function getImageUrlOutOfContent($content)
{
preg_match_all('/\\{IFTTTImageFetch="([^"]+)"\\}/i', $content, $matches);
$url = $matches[1][0];
importRemoteMedia($url, $post->ID);
$content = str_replace($url, "", $content);
return $content;
}
add_filter('content_save_pre', 'getImageUrlOutOfContent', 10, 1);
It should parse the prefix and the url - do the download stuff ... and remove it form the content ... but it does't even show a match... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "shortcode, customization"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.